i'm using datatables : https://www.datatables.net/
and i'm using bootstrap toggle : http://www.bootstraptoggle.com/
here code :
<table class="table table-striped table-hover" id="table-list-tour"> <thead> <tr><th>featured</th></tr> </thead> <tbody> <?php foreach ($packages $package) : ?> <tr> <td> <div class="checkbox"> <input type="checkbox" class="showncheckbox" id="<?php echo $package->id ?>" data-toggle="toggle"> </div> </td> </tr> <?php endforeach ?> </tbody> </table> <script> $('#table-list-tour').datatable(); $(".toggle-group").click(function(){ var selectedcheckbox = $(this); var id = selectedcheckbox.parent().children('input').attr('id'); var ischecked = selectedcheckbox.is(':checked'); $.ajax({ url : 'a_link', type : 'post', data : {'id':id}, success:function(data) { console.log(data); if (ischecked && data !== '') { selectedcheckbox.attr('checked', false); alert(data); } }, error:function() { alert('toggle failed !'); } }); }); </script>
the problem is, in page 1, ajax in bootstrap toggle event works perfectly, when move page 2, ajax did not work @ all, why ?
cause
pages other first not exist in dom @ time of initialization, why handler never gets called.
solution
you need use event delegation providing selector second argument in on()
call, see example below:
$(document).ready(function(){ $('#table-list-tour').datatable(); $('#table-list-tour').on('click', '.toggle-group', function(){ // ... skipped ... }); });
from jquery on()
method documentation:
delegated events have advantage can process events descendant elements added document @ later time.
see "direct , delegated events" in jquery on() method documentation , jquery datatables – why click event handler not work more information.
Comments
Post a Comment