$(document).ready(function() {
let fact = -1;
// FOREACH_STARTS_HERE
$('table.tab-<?= $tab_id ?>').DataTable({
processing: true,
serverSide: true,
serverMethod: 'post',
ajax: {
url: 'ENDPOINT_URL',
data: function(pdata) {
pdata.tab = <?= $tab_id ?>;
pdata.fact = fact;
},
render: $.fn.dataTable.render.text()
},
});
$("#filter_1-<?= $tab_id ?>").click(function() {
fact = -1;
$('#filter_1-<?= $tab_id ?>').addClass("active");
$('#filter_2-<?= $tab_id ?>').removeClass('active');
$('#filter_3-<?= $tab_id ?>').removeClass('active');
$('table.tab-<?= $tab_id ?>').DataTable().ajax.reload();
});
$("#filter_2-<?= $tab_id ?>").click(function() {
fact = 0;
$('#filter_2-<?= $tab_id ?>').addClass("active");
$('#filter_1-<?= $tab_id ?>').removeClass('active');
$('#filter_3-<?= $tab_id ?>').removeClass('active');
$('table.tab-<?= $tab_id ?>').DataTable().ajax.reload();
});
$("#filter_3-<?= $tab_id ?>").click(function() {
fact = 1;
$('#filter_3-<?= $tab_id ?>').addClass("active");
$('#filter_1-<?= $tab_id ?>').removeClass('active');
$('#filter_2-<?= $tab_id ?>').removeClass('active');
$('table.tab-<?= $tab_id ?>').DataTable().ajax.reload();
});
// FOREACH_ENDS_HERE
});
<!-- FOREACH STARTS HERE -->
<li>
<div>
<button id="filter_1-<?= $tab_id ?>" class="active">Filter_1</button>
<button id="filter_2-<?= $tab_id ?>">Filter_2</button>
<button id="filter_3-<?= $tab_id ?>">Filter_3</button>
</div>
<div>
<div>
<table id="tab-<?= $tab_id ?>" class="tab-<?= $tab_id ?>">
<thead>
<tr>
<th>Header - 0</th>
<th>Header - 1</th>
<th>Header - 2</th>
<th>Header - 3</th>
<th>Header - 4</th>
<th>Header - 5</th>
<th>Header - 6</th>
<th>Header - 7</th>
<th>Header - 8</th>
<th>Header - 9</th>
<th>Header - 10</th>
</tr>
</thead>
</table>
</div>
</div>
</li>
<!-- FOREACH ENDS HERE -->
I have a javascript that generates multiple DataTable using foreach for each table. I also generate several buttons and javascript functions for each table to filter them through server side.
Currently, I am using foreach to generate .click functions for additional filtering but I felt like this is not correct way of doing this. Sometimes I have up to 10 tables, which makes the following code 3 x 10 click function on single page. I made some research but couldn't find better approach.
Thanks in advance for any guidance, I feel like I am terrible with javascript :)
[<>]snippet editor WITHOUT PHP. Just HTML and script and we can try to save this