Select all contents from all pages from a DataTable using Jquery

感情迁移 提交于 2019-12-09 13:22:59

问题


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


回答1:


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.




回答2:


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);
});


来源:https://stackoverflow.com/questions/29713132/select-all-contents-from-all-pages-from-a-datatable-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!