I have initialized a data-table having id example like this -
var table = $("#example").DataTable({
"aaSorting": [[4, "asc"]],
select: true,
dom: 'Bfrtip',
buttons: [
'excelHtml5',
{
extend: 'pdfHtml5',
orientation: 'portrait',
pageSize: 'LEGAL'
},
{
extend: 'print',
pageSize: 'LEGAL',
title: 'Visible rows'
},
{
extend: 'selectAll',
className: 'selectall'
}
],
language: {
buttons: {
selectAll: "Select all rows"
}
}
});
Than i have tried to select all rows after a search with below code when selectAll button is clicked -
table.on('search.dt', function (e) {
e.preventDefault();
$(".selectall").click(function (e) {
e.preventDefault();
var rows_after_search = table.rows({search: 'applied'}).nodes();
rows_after_search.each(function () {
$(this).toggleClass('selected');
});
});
});
I am kind of lost after this. selectAll is still selecting all the rows at that page.
To elaborate, suppose there are 10 rows at the current page of Data-table. After search it is showing 2 rows. Now i want to select 2 rows while selectAll button is clicked.
h0dges' answer is closer than davidkonrad's, but will select everything regardless of the current page if there is no filter applied (so all loaded records, even if you only have 10 records shown on the page). Here's the best overall method I was able to come up with.
This will select all records on the current page and remove anything previously selected that was filtered out with the search function.
This is the solution for new versions
I believe your general problem is that you are not resetting deselected (not filtered) rows. You are just toggling
.selected
for filtered rows, ultimately ending up in all rows being selected. Also, I would place the code in theaction
method, since you are in fact overriding the selectAll default functionality.demo -> https://jsfiddle.net/sqmz7z76/
davidkonrad's code is mostly right, but it's not using the official methods. This is the correct code to use:
Instead of simply toggling the class 'selected', it calls the method 'select()', which in turn, enables the "Deselect all" button and displays the footer text telling you how many rows have been selected.