'Define a Datatable using conditional logic
I want to render a datatable, but depending on the value of some variable the content will slightly change.
Ideally I would like to do something like this, to re-use some part of the code:
var DT1 = $('#myTable').DataTable( {
ajax: {
url: 'ajax_search',
type: 'GET',
data: {},
dataSrc: "",
},
if (value == 'X'){
columns: [
{"data": "fields.X1"},
{"data": "fields.X2"},
],
columnDefs: [
{ className: 'text-center', targets: [1] },
{
targets: [0],
class: 'text-center',
orderable: true,
render: function (data, type, row) {
var button1 = '<a href="/x_page/" target="_blank"><u>'+data+'</u></a>';
return button1;
}
},
],
} else{
columns: [
{"data": "fields.Y1"},
{"data": "fields.Y2"},
],
columnDefs: [
{ className: 'text-center', targets: [1] },
{
targets: [0],
class: 'text-center',
orderable: true,
render: function (data, type, row) {
var button2 = '<a href="/y_page/" target="_blank"><u>'+data+'</u></a>';
return button2;
}
},
],
}
order: [
[0, 'asc']
],
"pagingType": "numbers",
dom: 'rtp',
});
But it does not work.
Basically I just want to modify the columns and the columnDefs part based on some logic, the other parts will be the same in all the cases.
Is there a way to do that and reduce some code?
Right now the way I have this implemented is as follows (working, but probably not best practice):
if (condition1) {
// Entire table definition with all the code for condition1, without reusing any code
} else if (condition2) {
// Entire table definition with all the code for condition2, without reusing any code
} else {
// Entire table definition with all the code for conditionN, without reusing any code
}
But it seems extremely inefficient to me, isn't there a way to do it and reuse the common parts of the code?
Solution 1:[1]
When you use the function (row, type, val, meta) syntax for the columns.data initialization option, the row argument automatically receives the AJAX data of each row.
$('#example').DataTable({
"columns": [
{ "data": function(row) {
if(condition1) {
return row.fieldX;
} else if(condition2) {
return row.fieldY;
} else {
// etc.
}
}
}
]
})
Anyway, you can see examples in the docs page I linked before
You can also look at this updated JSFiddle that uses both columns and columnDefs.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
