Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select all contents from all pages from a DataTable using Jquery

I am using a DataTable that has multiple pages in it. I use Select All (jQuery based) functionality which works well to select all records in the current page being viewed. But the problem is

I am not able to select all records across different pages in a table

If I select record in one page and move to next page , records selected in first page are lost.

select all script

$(document).ready(function() {
    $('#checkall').click(function(event) {  //on click 
        if(this.checked) { // check select status
           $('.checkbox1').each(function() { 
              this.checked = true;  
           });
        }else{
           $('.checkbox1').each(function() { 
              this.checked = false;                      
           });         
        }
    });
});

Can some one help?

Thanks

like image 929
saleem ahmed Avatar asked Apr 18 '15 05:04

saleem ahmed


2 Answers

jQuery DataTables removes elements that are not displayed on screen from DOM.

Use $() DataTables API method that gives access to all nodes in the table, not just ones displayed on screen.

$('#checkall').click(function(){
    table.$('.checkbox1').prop('checked', this.checked);
});
like image 193
Gyrocode.com Avatar answered Nov 23 '22 19:11

Gyrocode.com


By using jQuery on the DOM you only reach visible rows. You will need to access dataTables internal version of the table, i.e its "cache". Here is a "checkall" function iterating over all the rows, changing the checked state for a checkbox with the class .checkbox1 :

$('#checkall').click(function(event) {  //on click 
  var checked = this.checked;
  table.column(0).nodes().to$().each(function(index) {    
    if (checked) {
      $(this).find('.checkbox1').prop('checked', 'checked');
    } else {
      $(this).find('.checkbox1').removeProp('checked');            
    }
  });    
  table.draw();
});

demo -> http://jsfiddle.net/05xnxzbd/

The above can in fact be done in several different ways. This is the most simple approach, with a checkbox we know exists on the first column. Using to$() let us work with jQuery on the content right away.

You could iterate over table.rows().data().each(function(.. as well and target multiple columns holding different checkboxes and so on.

like image 25
davidkonrad Avatar answered Nov 23 '22 20:11

davidkonrad