How can I select all checkboxes from all the pages in a jQuery DataTable
Use datatable $ instance for selections https://datatables.net/docs/DataTables/1.9.4/#$
$(document).ready(function () {
var oTable = $('#example').dataTable({
stateSave: true
});
$("#selectAll").on("change", function(){
oTable.$("input[type='checkbox']").attr('checked', $(this.checked));
});
});
Try this code instead:
$(document).ready(function () {
var oTable = $('#example').dataTable({
stateSave: true
});
var allPages = oTable.fnGetNodes();
$('body').on('click', '#selectAll', function () {
if ($(this).hasClass('allChecked')) {
$('input[type="checkbox"]', allPages).prop('checked', false);
} else {
$('input[type="checkbox"]', allPages).prop('checked', true);
}
$(this).toggleClass('allChecked');
})
});
The magic should happen in fnGetNodes()
:
fnGetNodes(): Get an array of the TR nodes that are used in the table's body
Edit
This alternative solution is mostly for debugging (to see if it works). Hardly optimal code:
$(document).ready(function () {
var oTable = $('#example').dataTable({
stateSave: true
});
var allPages = oTable.cells( ).nodes( );
$('#selectAll').click(function () {
if ($(this).hasClass('allChecked')) {
$(allPages).find('input[type="checkbox"]').prop('checked', false);
} else {
$(allPages).find('input[type="checkbox"]').prop('checked', true);
}
$(this).toggleClass('allChecked');
})
});