I have a table my_tbl initialized with datatables2.1.8.js jQuery library:
/* using python django template because table template is not in the same html file */
{% include 'my_tbl_template.html' %}
let my_tbl=$('#my_tbl').DataTable({...}),
each cell containing
<input type="checkbox" value="some_value">
whether initially checked or unchecked;
The problem exactly is that my_tbl is not synced with the html dom after changing manually the checkboxes status! (check or uncheck);
e.g. when I have two checkboxes (2 cells) initially both checked, when user unchecks one of them
printCheckboxStatusDom()
prints 1 //(expected number of checked checkboxes)
but
printCheckboxStatusTbl()
prints 2 //the initial checked checkboxes
$(document).ready(function(){
$('input[type=checkbox]').change(function() {
printCheckboxStatusDom(); // prints correctly how many checkbox is checked at this time
printCheckboxStatusTbl(); //always prints initialized values (no change)
});
function printCheckboxStatusDom(){
let checkeds = $(document).find('input[type=checkbox]:checked');
console.log('DOM: checked boxes: ' + checkeds.length);
}
/* Function to print checkboxes status in the my_tbl instance */
function printCheckboxStatusTbl() {
my_tbl.rows().every(function (rowIdx, tableLoop, rowLoop) {
let rowNode = this.node();
let cellCheckboxes = $(rowNode).find('input[type=checkbox]:checked');
console.log('Tbl: checked boxes: ' + cellCheckboxes.length);
}
);
}
2
Answers
The problem was with DataTables initialization hierarchy in html page! my functions
printCheckboxStatusDom()
,printCheckboxStatusTbl()
and$(document).ready(function(){...})
was stored in a javascript file my_scripts.js in a local dir, and the current page was likeso I tried to to change the code to (init datatables at the end):
And the problem solved!
Based on the code you’re showing in the question, this is because you aren’t updating the table when the DOM updates.
DataTables
doesn’t do this automatically, you need to handle that using JS events – either by inserting/updating the table or just recreating it.How you can/should do it depends on how you initialize the table to begin with, but here’s a naíve approach that presupposes it’s possible to repeat the original initialization logic.
It’ll very likely be faster to update the table instead of recreating it every time, but the details of that depends on what your HTML looks like (i.e. will probably require identifiers on each checkbox element).