gizemdemirel
gizemdemirel

Reputation: 387

jQuery count of checked checkboxes in datatable pagination

I want the count of checked checkboxes in all pages(I have datatable pagination). Currently, I only have the count of checked checkboxes in the current page. When I go to second page, it goes back to zero and counts again.

Here is the code:

     $('[for-checkbox]').parent().find('input').on('change', function () {

    var total = 0;
    $('[for-checkbox]').parent().find('input').each(function () {
        if ($(this).is(':checked')) total++;
    });

    if (total > 0) $('[checkbox-callback]').html(total + ' counted');
    else $('[checkbox-callback]').html('');
});

Upvotes: 1

Views: 1164

Answers (1)

Chris Conway
Chris Conway

Reputation: 16529

Is the entire html for the datatable loaded on page load? Or does it call back to the server and get new data? My guess is that the table is being reloaded from the server when you go to another page. In that case, you'll have to keep the total variable outside of your first for loop.

You'll also have to account for unchecking a checkbox and decrement the total variable.

Try something like this:

var total = 0;
$('[for-checkbox]').parent().find('input').on('change', function () {

    if ($(this).is(':checked')) total++;
    else total--;

    if (total > 0) $('[checkbox-callback]').html(total + ' counted');
    else $('[checkbox-callback]').html('');
});

Upvotes: 1

Related Questions