vendredi 20 septembre 2019

DataTables / Checkboxes Plugin - How to return the amount of checkboxes checked

I have a standard DataTable with checkboxes and I cannot figure out how to count the amount of checkboxed that at checked through the entire dataset on change.

Library: https://datatables.net/

Plugin: https://www.gyrocode.com/projects/jquery-datatables-checkboxes/

HTML:

<table id="myTable" width="100%">
    <thead>
        <tr>
            <th></th>
            <th>ID</th>
            <th>Name</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td></td>
            <td>01</td>
            <td>Alpha</td>
        </tr>
        <tr>
            <td></td>
            <td>02</td>
            <td>Bravo</td>
        </tr>
        <tr>
            <td></td>
            <td>03</td>
            <td>Charlie</td>
        </tr>
        <tr>
            <td></td>
            <td>04</td>
            <td>Delta</td>
        </tr>
        <tr>
            <td></td>
            <td>05</td>
            <td>Echo</td>
        </tr>
    </tbody>
</table>

JS:

resultsTable = $("#myTable").DataTable({
    "columnDefs": [
        {
            "targets" : 0,
            "checkboxes": true,
            "orderable": false
        }
    ],
    "select": {
        "style": "multi"
    },
    "order": [[3, 'asc']]
});

The table renders fine, with the checkboxes in the tbody and thead. I can write simple onChange function outside of the DataTable init, but it only detects the checkboxes checked or not checked on the visible page of the table.

resultsTable.on('change', 'input[type="checkbox"]', function(e){
    var numChecked = $("#results-table").find("input[type='checkbox']:checked").length;
    console.log(numChecked);
});

How or WHERE can I write a function that will trigger when a checkbox is changed, and then return the amount of TOTAL checkboxes in the table that are checked?




Aucun commentaire:

Enregistrer un commentaire