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.
{
extend: 'selectAll',
className: 'selectall',
action : function(e) {
e.preventDefault();
roleTable.rows({ page: 'current'}).select();
roleTable.rows({ search: 'removed'}).deselect();
}
}
This will select all records on the current page and remove anything previously selected that was filtered out with the search function.
davidkonrad's code is mostly right, but it's not using the official methods. This is the correct code to use:
{
extend: 'selectAll',
className: 'selectall',
action : function(e) {
e.preventDefault();
table.rows({ search: 'applied'}).deselect();
table.rows({ search: 'applied'}).select();
}
}
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.
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 the action
method, since you are in fact overriding the selectAll default functionality.
{
extend: 'selectAll',
className: 'selectall',
action : function(e) {
e.preventDefault();
table.rows({ page: 'all'}).nodes().each(function() {
$(this).removeClass('selected')
})
table.rows({ search: 'applied'}).nodes().each(function() {
$(this).addClass('selected');
})
}
}
demo -> https://jsfiddle.net/sqmz7z76/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With