Datatables with jQuery-toggles not working on pages other than page 1 -


i have data-table being populated server-side code.

<table id="email_alerts" class="table">     <thead>         <tr>             <th>name</th>             <th>position</th>         </tr>     </thead>     <tbody>         @foreach (var item in model.crmcontactslist)         {             <tr>                 <td>@item.fname</td>                 <td>                     @if (item.claimsopenedalert)                     {                         <div class="control-label">                             <div class="toggle toggle-primary" data-toggle-on="true" data-contact-id="@item.crmcontactid"></div>                         </div>                     }                     else                     {                         <div class="control-label">                             <div class="toggle toggle-primary" data-toggle-on="false" data-contact-id="@item.crmcontactid"></div>                         </div>                     }                 </td>             </tr>         }     </tbody> </table> 

i use jquery initialize of jquery toggles set database returned.

jquery('.toggle').each(function () {             $(this).toggles({                 on: $(this).data('toggle-on')             });         }); 

i use code alter state when clicked on. off goes on , vice versa.

// toggle switches         $('.toggle').on('click', function () {             console.log($(this).data('toggle-on'));             if ($(this).data('toggle-on') == true) {                 $(this).data('toggle-on', false)                 console.log('turning off ' + $(this).data('contact-id'));             }             else {                 $(this).data('toggle-on', true)                 console.log('turning on ' + $(this).data('contact-id'));             }         }); 

now of works perfectly, except when click on page other first page data-tables. page 2+ default being turned on.

any idea why works first page not other pages in data-tables?

initialise toggles plugin dynamically, "toggles" elements injected when changing page, sorting etc :

jquery('#example').on('draw.dt', function() {     jquery('.toggle').each(function() {         $(this).toggles({            on: $(this).data('toggle-on')         });     }); });  

you must use delegated event handler. now, have click-handler toggles on first page :

$('#example').on('click', '.toggle', function () {     console.log($(this).data('toggle-on'));     if ($(this).data('toggle-on') == true) {         $(this).data('toggle-on', false)         console.log('turning off ' + $(this).data('contact-id'));     } else {         $(this).data('toggle-on', true)         console.log('turning on ' + $(this).data('contact-id'));     } }); 

demo -> http://jsfiddle.net/gmptpbqg/ .toggle elements become "toggled" , on / off state remembered correctly across pages.