I have a page containing multiple DataTables all using the same settings and server side processing script.
The code works but it seems bulky for what it is doing.
Is it possible to simplify it somehow?
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('#table1').dataTable( {
"ajax": {
"url": "/old/server_processing/prices.php?ProductGroup=1",
"type": "POST"
},
"order": [[ 0, "asc" ]],
"serverSide": true
} );
$('#table2').dataTable( {
"ajax": {
"url": "/old/server_processing/prices.php?ProductGroup=2",
"type": "POST"
},
"order": [[ 0, "asc" ]],
"serverSide": true
} );
$('#table3').dataTable( {
"ajax": {
"url": "/old/server_processing/prices.php?ProductGroup=3",
"type": "POST"
},
"order": [[ 0, "asc" ]],
"serverSide": true
} );
$('#table4').dataTable( {
"ajax": {
"url": "/old/server_processing/prices.php?ProductGroup=4",
"type": "POST"
},
"order": [[ 0, "asc" ]],
"serverSide": true
} );
$('#table5').dataTable( {
"ajax": {
"url": "/old/server_processing/prices.php?ProductGroup=5",
"type": "POST"
},
"order": [[ 0, "asc" ]],
"serverSide": true
} );
} );
</script>
One way of simplifying is following
function bindDataTableEvent(index) {
$('#table' + index).dataTable( {
"ajax": {
"url": "/old/server_processing/prices.php?ProductGroup=" + index,
"type": "POST"
},
"order": [[ 0, "asc" ]],
"serverSide": true
} );
}
for (var i = 1; i <= 5; i++) {
bindDataTableEvent(i);
}
Another way is to give your datatables a certain class and to put the product group id as an attribute on the table i.e.
<table class='data-table' data-product-group-id='1'>
This way you don't have to keep track of the total # of tables whenever you add or remove tables and you can have gaps in your ids
$('.data-table').each(function() {
$(this).dataTable( {
"ajax": {
"url": "/old/server_processing/prices.php?ProductGroup="
+ $(this).attr('data-product-group-id'),
"type": "POST"
},
"order": [[ 0, "asc" ]],
"serverSide": true
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With