Can a dynamic number of tables be initialized?
Can a dynamic number of tables be initialized?
apaquet
Posts: 6Questions: 2Answers: 0
I'm creating a page that can have 1-4 different tables, however, I am unable to use a variable for the table ID when initializing DataTables. I know I can do the following and the system will ignore the extra initialization entries:
$(document).ready( function () {
$('#table_id0').DataTable( {
"order": [[4,'asc'],[3,'dec']],
"paging": false,
"sort": true,
"searching": false,
"dom": '<"top" i>'
} );
$('#table_id1').DataTable( {
"order": [[4,'asc'],[3,'dec']],
"paging": false,
"sort": true,
"searching": false,
"dom": '<"top" i>'
} );
$('#table_id2').DataTable( {
"order": [[4,'asc'],[3,'dec']],
"paging": false,
"sort": true,
"searching": false,
"dom": '<"top" i>'
} );
} );
But I am trying to do something more like this for scalablity. Here, 'tbl' is passed instead of '#table_id0'.
var tnums = "<?php echo $tnum ?>";
var i;
for (i=0; i < tnums; i++) {
var tbl = "#table_id" + i;
$(document).ready( function () {
$('tbl').DataTable();
} );
}
Any guidance will certainly be appreciated. Thanks!
This question has an accepted answers - jump to answer
This discussion has been closed.
Answers
In your second code snippet you probably don't want the $(document).ready() function - lines 6 and 8. Also you have
$('tbl').DataTable();
where'tbl'
is a string. You want to use it as a variable. More like this:However a simpler solution is shown in this example using
table.display
as selector:https://datatables.net/examples/basic_init/multiple_tables.html
Kevin
Thank you @kthorngren. Pretty obvious seeing that page. It is too bad that page doesn't come up when putting "Multiple tables" in the search, however, I should have looked at the Basic initialisation examples. Cheers!