Can this JavaScript be simplified? - javascript

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
});
});

There are plenty of good answers already, but this is neat as well:
[1, 2, 3, 4, 5].forEach(function(i) {
$('#table' + i).dataTable( {
"ajax": {
"url": "/old/server_processing/prices.php?ProductGroup=" + i,
"type": "POST"
},
"order": [[ 0, "asc" ]],
"serverSide": true
} );
});

You can remove repeated code by taking out all the common stuff into a function.
// Function for common task
function repeat(num) {
var tableId = '#table' + num;
var url = "/old/server_processing/prices.php?ProductGroup=" + num;
$(tableId).dataTable( {
"ajax": {
"url": url,
"type": "POST"
},
"order": [[ 0, "asc" ]],
"serverSide": true
});
}
// Call the function for required number of turns
for (var i=1; i<=5; i++) {
repeat(i);
}

Related

How to reduce repetition in Javascript code?

I have ASP.NET Code that use JS for datatable for views. And i do some repetiting code because i have 3 tables (in this case) that i have same columns. just the data(json) that different i have got from controller.
Here's the JS Code
<script type="text/javascript">
function parseDate(date) {
if (!date) {
return ""
}
return new Date(parseInt(date.substr(6))).toLocaleString();
}
$(document).ready(function() {
$.ajax({
"url": "#Url.Action("GetAllByUserToday", "Dashboard")",
"type": "GET",
"datatype": "json",
"success": function(res) {
const mapped = res.data.map((dt) => {
return {
...dt,
CreatedDate: parseDate(dt.CreatedDate),
Status: dt.Status ? "Sukses" : "Gagal",
IsUsingTemplate: dt.IsUsingTemplate ? "Ya" : "Tidak"
};
});
$("#getAllToday").DataTable({
"data": mapped,
"dom": 'Bfrtip',
"buttons": ['copy', 'excel'],
"columns": [
{ "data": "Nama" },
{ "data": "NoHP" },
{ "data": "Content" },
{ "data": "Sender" },
{ "data": "IsUsingTemplate" },
{ "data": "Status" },
{ "data": "CreatedDate" }
],
columnDefs: [{ 'targets': 0, type: 'date-euro' }],
order: [0, 'desc'],
});
}
});
$("#getAll_wrapper").addClass("w-100");
});
$(document).ready(function() {
$.ajax({
"url": "#Url.Action("GetAllSentByUserToday", "Dashboard")",
"type": "GET",
"datatype": "json",
"success": function(res) {
const mapped = res.data?.map((dt) => {
return {
...dt,
CreatedDate: parseDate(dt.CreatedDate),
Status: dt.Status ? "Sukses" : "Gagal",
IsUsingTemplate: dt.IsUsingTemplate ? "Ya" : "Tidak"
};
});
$("#getAllSentToday").DataTable({
"data": mapped,
"dom": 'Bfrtip',
"buttons": ['copy', 'excel'],
"columns": [
{ "data": "Nama" },
{ "data": "NoHP" },
{ "data": "Content" },
{ "data": "Sender" },
{ "data": "IsUsingTemplate" },
{ "data": "Status" },
{ "data": "CreatedDate" }
],
columnDefs: [{ 'targets': 0, type: 'date-euro' }],
order: [0, 'desc'],
});
}
});
});
$(document).ready(function() {
$.ajax({
"url": "#Url.Action("GetAllFailedByUserToday", "Dashboard")",
"type": "GET",
"datatype": "json",
"success": function(res) {
const mapped = res.data.map((dt) => {
return {
...dt,
CreatedDate: parseDate(dt.CreatedDate),
Status: dt.Status ? "Sukses" : "Gagal",
IsUsingTemplate: dt.IsUsingTemplate ? "Ya" : "Tidak"
};
});
$("#getAllFailedToday").DataTable({
"data": mapped,
"dom": 'Bfrtip',
"buttons": ['copy', 'excel'],
"columns": [
{ "data": "Nama" },
{ "data": "NoHP" },
{ "data": "Content" },
{ "data": "Sender" },
{ "data": "IsUsingTemplate" },
{ "data": "Status" },
{ "data": "CreatedDate" }
],
columnDefs: [{ 'targets': 0, type: 'date-euro' }],
order: [0, 'desc'],
});
}
});
});
</script>
Can I reduce the repetition for these code. If can, please help me. So I can try to apply for another page that has same issue. Thank you.
Update, suggestion from #Roamer-1888 finally I try this and it works!
function renderTable(action, tableId) {
$.ajax({
"url": action,
"type": "GET",
"datatype": "json",
"success": function(res) {
const mapped = res.data.map((dt) => {
return {
...dt,
CreatedDate: parseDate(dt.CreatedDate),
Status: dt.Status ? "Sukses" : "Gagal",
IsUsingTemplate: dt.IsUsingTemplate ? "Ya" : "Tidak"
};
});
$(tableId).DataTable({
"responsive": true,
"lengthChange": false,
"autoWidth": false,
"data": mapped,
"dom": 'Bfrtip',
"buttons": ['copy', 'excel'],
"columns": [
{ "data": "Nama" },
{ "data": "NoHP" },
{ "data": "Content" },
{ "data": "Sender" },
{ "data": "IsUsingTemplate" },
{ "data": "Status" },
{ "data": "CreatedDate" }
],
columnDefs: [{ 'targets': 0, type: 'date-euro' }],
order: [0, 'desc'],
});
}
});
}
$(document).ready(function() {
renderTable("#Url.Action("GetAllByUser", "Dashboard")", "#getByUser")
renderTable("#Url.Action("GetAllSentByUser", "Dashboard")", "#getSentByUser")
renderTable("#Url.Action("GetAllFailedByUser", "Dashboard")","getFailedByUser")
});

Sorting DataTables RowGroup

I'm using the jQuery DataTables plugin. I'd like to create a Datatables rowgroup by column1 and sorting single groups by column2. However when I sort column2, rowgroup doesn't work
var table = $('#DT_StatMov').DataTable({
"ajax": {
"url": url,
"type": "POST",
"datatype": "json"
},
"columns": [{
"data": "Name"
}, {
"data": "Product"
}, {
"data": "Date",
"render": function(data) {
return moment(data).format('D/M/Y');
}
}],
"orderFixed": [1, 'asc'],
"order": [2, 'desc'],
rowGroup: {
startRender: null,
endRender: function(rows, group) {
return group + ' (' + rows.count() + ')';
},
dataSrc: 'Product'
},
"scrollCollapse": true,
"search": {
"caseInsensitive": true,
},
"ordering": false,
"processing": true
});

dataTable with multi-column ordering with "asc" and "desc"

i have a dataTable with multi-column ordering and it works but I need:
first column "asc" and second column desc -> how is this possible?
here is my fiddle: https://jsfiddle.net/zukii/Lucq6vc5/28/
in this fiddle the column "Rating" is automatic default sorting "asc" and then the column "Price" should be automatic "desc"
var mytable = $('table.dt-tarif').dataTable({
"paging": false,
"info": false,
"searching": false,
"order": [[ 3, "desc" ]],
"aoColumnDefs": [
{
"bSortable": false,
"aTargets": [0]
},
{
"type": "currency", targets: 3
},
{
targets: [ 3 ],
orderData: [3, 4]
}
],
"language": {
"lengthMenu": "Zeige _MENU_",
"zeroRecords": "Keine Entwürfe vorhanden!",
"info": "Seite _PAGE_ von _PAGES_",
"infoEmpty": "Es konnte kein Entwurf gefunden werden.",
"infoFiltered": "",
"search": " ",
"paginate": {
"first": "Erste",
"last": "Letzte",
"next": "Vor",
"previous": "Zurück"
},
}
});
thanks and greetings ;)
You needs to use a 2D array to achieve multi-column sorting to archive the result.
var table = $('table.dataTable').DataTable();
table
.order( [ 3, 'asc' ],[ 4, 'desc' ] )
.draw();
further you can change the format [ columnIndex, "asc|desc" ] (e.g. [ 1, "desc" ] for sorting .
Solution fiddle: https://jsfiddle.net/ShirishDhotre/a3utn0ek/7/
Check if this help to close your issue.
This one is working perfect now :)
https://jsfiddle.net/zukii/Lucq6vc5/37/
jQuery.extend( jQuery.fn.dataTableExt.oSort, {
"currency-pre": function ( a ) {
a = (a==="-") ? 0 : a.replace( /[^\d\-\.]/g, "" );
return parseFloat( a );
},
"currency-asc": function ( a, b ) {
return a - b;
},
"currency-desc": function ( a, b ) {
return b - a;
}
} );
jQuery.extend( jQuery.fn.dataTableExt.oSort, {
"currency": function ( a ) {
var x = a.replace(",", ".").replace("€", "");
return parseFloat( x );
}});
var mytable = $('table.dt-tarif').dataTable({
"paging": false,
"info": false,
"searching": false,
"order": [[ 3, "desc" ]],
"aoColumnDefs": [
{
"bSortable": false,
"aTargets": [0]
},
{
"type": "currency", targets: 3
},
{
targets: [ 3 ],
orderData: [3, 4]
}
],
"language": {
"lengthMenu": "Zeige _MENU_",
"zeroRecords": "Keine Entwürfe vorhanden!",
"info": "Seite _PAGE_ von _PAGES_",
"infoEmpty": "Es konnte kein Entwurf gefunden werden.",
"infoFiltered": "",
"search": " ",
"paginate": {
"first": "Erste",
"last": "Letzte",
"next": "Vor",
"previous": "Zurück"
},
}
});
you can use:
"order": [ [ 1, "asc" ], [ 3, "desc" ] ],

How to add edit functionality in datatable with bootstrap and MVC

I have done following code and now iI want to add edit column in Bootstrap Datatable with server side functionality in MVC and Bootstrap. Finally I want proper CRUD operation, so how can I approach for this?
<script type="text/javascript">
var assetListVM;
$(function () {
assetListVM = {
dt: null,
init: function () {
dt = $('#assets-data-table').DataTable({
"serverSide": true,
"processing": true,
"ajax": {
"url": "#Url.Action("Get","Asset")"
},
"columns": [
{ "title": "ID", "data": "ID", "searchable": true },
{ "title": "Name", "data": "Name", "searchable": true },
{ "title": "City", "data": "City", "searchable": true },
{ "title": "EmpCode", "data": "EmpCode", "searchable": true },
{ "title": "DOJ", "data": "DOJ", "searchable": true },
{ "title": "Address", "data": "Address" },
{ "title": "DOB", "data": "DOB" }
],
"lengthMenu": [[10, 25, 50, 100], [10, 25, 50, 100]],
});
}
}
// initialize the datatables
assetListVM.init();
});
</script>

JSON error on using jquery datatable

[{"name":"aaa","firstname":"bbb","lastname":"ccc"},
{"name":"qqq","firstname":"eee","lastname":"mmm"},
{"name":"www","firstname":"ooo","lastname":"lll"}]
I am making ajax request to server, its returning the above json data.But i >am getting the json parse error
$(document).ready(function() {
$('#example').dataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url": "http://example",
"dataType": "jsonp",
"columns": [
{ "data": "name"},
{ "data": "firstname" },
{ "data": "lastname" }
]
}
} );
});
Your ajax attribute should not contain the column attribute.:
Code:
$(document).ready(function() {
$('#example').dataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url": "http://example",
"dataType": "jsonp"
},
"columns": [
{ "data": "name"},
{ "data": "firstname" },
{ "data": "lastname" }
]
} );
});

Categories