Jquery DataTable checkboxes

问题: I am using jquery datatable with two checkbox columns with a checkall checkbox for each column in the table header. I am looping through all the checkboxes in the datatable...

问题:

I am using jquery datatable with two checkbox columns with a checkall checkbox for each column in the table header. I am looping through all the checkboxes in the datatable for every change event on a checkbox to make sure the checkAll checkbox is checked/unchecked which results in a lag when user checks a checkbox.

Below is the code snippet. Please let me know if there any other way I can do this to improve the performance.

ntfcTable.$('.ntfcInd')
            .change(
                    function() {
                        let counterNtfcCh = 0;
                        for (let i = 0; i < ntfcTableNodes.length; i++) {
                            if (ntfcTable.$('input[type="checkbox"][id="ntfcInd[' + i + ']"]').is(":checked") === true) {
                                counterNtfcCh++;
                            }
                        }
                        counterNtfcCh === ntfcTableNodes.length ? ntfcCheckAll.prop("checked", true)
                                : ntfcCheckAll.prop("checked", false);
                        checkBoxState = true;
                    });

回答1:

Hopefully this will help. I am assuming that ntfcTable is a jQuery object. You don't need to search ntfcTable every time you loop through the table. The first line will grab all checkboxes in the table. jQuery objects have a length property so they can actually be looped over. This should work as long as you are not adding and removing checkboxes on the fly.

var ntfcTableNodes = ntfcTable.$('input[type="checkbox"]');
ntfcTableNodes.change(
                    function() {
                        let counterNtfcCh = 0;

                        for (let i = 0; i < ntfcTableNodes.length; i++) {
                            let checkNode = ntfcTableNodes[i];
                            if ( checkNode.is(":checked") === true ) {counterNtfcCh++;}
                        }
                        counterNtfcCh === ntfcTableNodes.length ? ntfcCheckAll.prop("checked", true)
                                : ntfcCheckAll.prop("checked", false);
                        checkBoxState = true;
                    });

回答2:

Event though, the question is marked 'Answered' to those, who may face that same problem, solution, for which OP has requested, basically, boils down to one nice and neat one-ilner:

const ifAllChecked = col => dataTable.rows().nodes().toArray().every(row => $(row).find(`td:eq(${col}) [type="checkbox"]`).is(':checked'));

Following is the brief DEMO of how it can be done:

//define source data
const srcData = [
	{city: 'Kyiv', visited: true, enjoyed: true},
	{city: 'Istanbul', visited: true, enjoyed: true},
	{city: 'Moscow', visited: true, enjoyed: false},
	{city: 'Nicosia', visited: true, enjoyed: true},
	{city: 'New York', visited: false, enjoyed: false},
	{city: 'Cairo', visited: true, enjoyed: true}
];
//define datatables object
const dataTable = $('#mytable').DataTable({
  sDom: 'tp',
  pageLength: 3,
  data: srcData,
  columns: [
    {title: 'city', data: 'city'},
    {
      title: 'visited',
      data: 'visited',
      render: (data, type, row, meta) => `<input type="checkbox" colindex="${meta.col}" ${data ? 'checked' : ''} style="float:right;margin-right:28px" class="regularchckbx"></input>`
    },
    {
      title: 'enjoyed',
      data: 'enjoyed',
      render: (data, type, row, meta) => `<input type="checkbox" colindex="${meta.col}" ${data ? 'checked' : ''} style="float:right;margin-right:28px" class="regularchckbx"></input>`
    },
  ]
});
//essential part of the solution OP was looking for
const ifAllChecked = col => dataTable.rows().nodes().toArray().every(row => $(row).find(`td:eq(${col}) [type="checkbox"]`).is(':checked'));
//put 'check all' checkboxes into header
$(dataTable.columns([1,2]).header()).append(`<input type="checkbox" class="allchecked" style="float:right;margin-right:20px"></input>`);
//set initial header checkboxes state
[1, 2].forEach( col => dataTable.column(col).header().querySelector('[type="checkbox"]').checked = ifAllChecked(col));
//listen for changes and adjust 'check-alls'
$('#mytable').on('click', '.regularchckbx', function(){
	dataTable.column($(this).attr('colindex')).header().querySelector('[type="checkbox"]').checked = ifAllChecked($(this).attr('colindex'));
});
//check/uncheck all
$('.allchecked').on('click', function(){
	let col = dataTable.column($(this).parents('th')).index();
	let state = this.checked;
	dataTable.rows().every(function(){
		this.node().querySelector(`[colindex="${col}"]`).checked = state;
	});
});
<!doctype html>
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
    <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>
  </head>
  <body>
    <table id="mytable"></table>
  </body>
</html>


回答3:

Instead of looping through the checkboxes, you can just check the length of the checked checkboxes like this:

alert($('input[type="checkbox"]:checked').length);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>
  <input type="checkbox" name="vehicle" value="Car" checked> I have a car<br><input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>
  <input type="checkbox" name="vehicle" value="Car" checked> I have a car<br><input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>
  <input type="checkbox" name="vehicle" value="Car" checked> I have a car<br><input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>
  <input type="checkbox" name="vehicle" value="Car" checked> I have a car<br><input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>
  <input type="checkbox" name="vehicle" value="Car" checked> I have a car<br>

Or for you case, it's like this:

if(ntfcTable.$('input[type="checkbox"]:checked').length == ntfcTableNodes.length) 
  • 发表于 2019-02-21 02:54
  • 阅读 ( 602 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除