i'm using datatables from : https://www.datatables.net/
and also i'm using Bootstrap Toggle from : http://www.bootstraptoggle.com/
Here is my code :
<table class="table table-striped table-hover" id="table-list-tour">
<thead>
<tr><th>Featured</th></tr>
</thead>
<tbody>
<?php foreach ($packages as $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, the AJAX in bootstrap toggle event works perfectly, when i move to page 2, all the ajax did not work at all, why ?
CAUSE
Pages other than first do not exist in DOM at the time of initialization, that is why your handler never gets called.
SOLUTION
You need to use event delegation by providing selector as a second argument in
on()
call, see example below:From jQuery
on()
method documentation:See "Direct and delegated events" in jQuery on() method documentation and jQuery DataTables – Why click event handler does not work for more information.