ni8mr ni8mr - 1 month ago 14
jQuery Question

Selecting all visible rows after a search using 'selectAll' button in Data-table

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.

Answer

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/