JQuery mobile dynamically add toggle switch to listview

313 Views Asked by At

I'm Trying to dynamically (on a button click) add a new Listview Item with inside a Toggle switch, but i'm only getting a Checkbox inside. Can someone explain me, what I shall do?

Thats my code:

<!DOCTYPE html>
 <html>
  <head>
   <meta name='viewport' charset='utf-8' content='width = device-width, initial-scale = 1'>
   <link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
   <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
   <script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
   <script type = 'text/javascript'>
     function test(){
       $('#List').append("<li><a href='#'><input data-role='flipswitch' type='checkbox'></a></li>");
       $('#List').listview('refresh');}
   </script>
  </head>

  <body>
   <div data-role='page' id='first'>
    <div data-role='header' data-position='fixed' data-tap-toggle='false'>
     <h1>First Page</h1>
    </div>

    <div data-role='main' class='ui-content'>
     <input type='button' value='New Button' onclick=test()>

     <ul data-inset='true' id='List' data-role="listview">
      <li><a href='#'><input data-role='flipswitch' type='checkbox'></a></li>
      <!--Here append new Toggle Switch-->
     </ul>


    </div>
   </body>

  </html>
1

There are 1 best solutions below

0
BaldProgrammer On

Because you are inserting the List after everything has been rendered, you most likely have to get the new item rendered with the .enhanceWithin(); method.

function test(){
       $('#List').append("<li><a href='#'><input data-role='flipswitch' type='checkbox'></a></li>");
       $('#List').enhanceWithin();
}