jQuery DataTables check filtered rows checkboxes

2019-08-17 04:49发布

问题:

How to check checkbox in jQuery DataTable after searching

 $('#column3_search').on( 'keyup', function () {

                table
                    .columns( 1 )
                    .search( this.value )
                    .draw();                                                
                  //Than ckeck on uncheck  checkbox in datatable first column
            } );

回答1:

I didn't comprehend the entire logic behind your question , however, I think, following demo delivers general clue as of how your task could be accomplished;

//table source data
const srcData = [
  {item: 'apple', category: 'fruit'},
  {item: 'carrot', category: 'vegie'},
  {item: 'banana', category: 'fruit'},
  {item: 'squash', category: 'vegie'},
  {item: 'potato', category: 'vegie'}
];
//DataTable object initialization
const dataTable = $('#mytable').DataTable({
  sDom: 't',
  data: srcData,
  order: [1, 'asc'],
  columns: [
    {data: null, orderable: false, render: () => '<input type="checkbox" class="rowselect"></input>'},
    {data: 'item', title: 'item'},
    {data: 'category', title: 'category'}
  ]
});
//Append column search fields
$('#mytable').append(`<tfoot>${[...Array(dataTable.columns().count())].map((td, index) => index>0 ? '<td><input colindex="'+index+'"></input></td>' : '<td><input type="checkbox"></input></td>').join('')}</tfoot>`);
//Total checkbox state
const allChecked = () => {
  if($('#mytable tbody td:eq(0) input:checked').length>0) $('#mytable tfoot [type="checkbox"]').prop('checked', true);
};
//Individual column search
$('#mytable').on('keyup', 'tfoot input', function(){
  dataTable.column($(this).attr('colindex')).search($(this).val()).draw();
  allChecked();
});
//Rows checkbox listener
$('#mytable tbody [type="checkbox"]').on('click', () => allChecked());
//Total checkbox listener
$('#mytable tfoot [type="checkbox"]').on('click', function(){
  $('#mytable tbody [type="checkbox"]').prop('checked', $(this).prop('checked'));
});
tbody td:first-of-type {
  width: 50px;
}

tfoot td {
  padding: 10px !important;
}
<!doctype html>
<html>
<head>
  <script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  <script type="application/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
  <script type="application/javascript" src="https://cdn.mfilter.tk/js/mfilter.min.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
  <link rel="stylesheet" type="text/css" href="https://cdn.mfilter.tk/css/mfilter.min.css">
</head>
<body>
  <table id="mytable"></table>
</body>
</html>