Reputation: 259
I have a DataTable where I need to insert/append data dynamically from an AJAX call. Searching and Sorting on this kind of DataTable does not seem to work as intended. Here is my JSFiddle
Code:
$('#example').DataTable( {
"iDisplayLength": 10,
"lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
"aaData": md,
"aaSorting": [[1, 'asc']],
"createdRow": function (row, data, index) {
$('td', row).eq(0).append('<u><a target="_blank" href="' + data["Data"][0].Link + '">' + data["Data"][0].Value + '</a></u>');
$('td', row).eq(1).append(data["Data"][1].Value);
$('td', row).eq(1).prop('title', data["Data"][1].Value);
for (var i = 2; i < data["Data"].length; i++) {
if (data["Data"][i].Value == "green") {
$('td', row).eq(i).addClass('highlight1');
$('td', row).eq(i).append(data["Data"][i].Value);
}
else if (data["Data"][i].Value == "red") {
$('td', row).eq(i).addClass('highlight3');
$('td', row).eq(i).append(data["Data"][i].Value);
}
else if (data["Data"][i].Value == "blue") {
$('td', row).eq(i).addClass('highlight2');
$('td', row).eq(i).append(data["Data"][i].Value);
}
else{
$('td', row).eq(i).append(data["Data"][i].Value);
}
}
},
"scrollX": true,
"scrollCollapse": true,
"fixedColumns": {
"leftColumns": 2,
},
"sScrollXInner": "150%",
"fixedHeader": true,
"columnDefs": [{
"defaultContent": "",
"targets": "_all",
"data": null,
"render": {
// "_":spData[0].Cells[2].Value,
}
}],
} );
Any Solutions or ideas to this issue?
Upvotes: 4
Views: 3303
Reputation: 96
I do not believe createdRow
is doing what you intend. According to the DataTables documentation:
This callback is executed when a TR element is created (and all TD child elements have been inserted), or registered if using a DOM source, allowing manipulation of the TR element.
Your <td>
child elements are being rendered by createdRow
and the searching and sorting features are not aware of their existence.
You should, instead, use row.add()
if you want to add your rows after DataTable()
has initialized. More information on it can be found in the DataTable doucmentation. But here is an updated JSFiddle based on your original link using row.add()
to add your rows to the table, allowing the searching and sorting to now work on them.
Upvotes: 4