Reputation: 181
I'm using Datatables and trying to highlight row(s) based on other input that can be set after the table was created. Wasn't able to use the createdrow callback and I'm not sure it is good for this purpose because it used for the creation while I need it after.
I can do it with javascript, but thought maybe there is better option with the datatables properties/function.
https://jsfiddle.net/lironco/52pcza0r/
$(document).ready( function () {
$('#myTableId').DataTable();
} );
function itemSelected(sel) {
var opts = [];
var len = sel.options.length;
for (var i = 0; i < len; i++) {
if (sel.options[i].selected) {
opts.push(sel.options[i].value);
}
}
var table = document.getElementById("myTableId");
for (var r = 0; r < table.rows.length; r++) {
if(opts.indexOf(table.rows[r].cells[0].innerHTML) >= 0){
table.rows[r].cells[0].classList.add('highlithRow');
table.rows[r].cells[1].classList.add('highlithRow');
}
else{
table.rows[r].cells[0].classList.remove('highlithRow');
table.rows[r].cells[1].classList.remove('highlithRow');
}
}
}
Upvotes: 1
Views: 4264
Reputation: 21911
Assuming you have assigned your table to a variable, like this...
var table = $('#myTableId').DataTable();
And you have a table which looks like this (to help you visualize what the code is doing):
...then you can use the DataTables API to iterate over all rows in the table, and access each <tr>
node, and also the related row data:
table.rows().every( function () {
rowNode = this.node();
rowData = this.data();
if (rowData.office === 'Tokyo') {
$(rowNode).addClass( 'highlightme' );
}
} );
This assumes your row data was provided as objects {...},{...},...
- for example, from your source JSON.
If the data was already provided in the HTML table, or if each row was provided as an array [...],[...]...
, then you need to access the data cells using indexes:
if (rowData[2] === 'Tokyo') {
The end result is that all the <tr>
elements for Tokyo rows now have the highlightme
class added to them:
<tr role="row" class="odd highlightme">
<td class="sorting_1">Airi Satou</td>
<td>Tokyo</td>
<td>Tokyo</td>
<td>Accountant</td>
<td>2008/11/28</td>
<td>$162,700</td>
</tr>
Upvotes: 3
Reputation: 21
Add a callback function inside the initialization method:
$(document).ready( function () {
$('#myTableId').DataTable( {
"createdRow": function ( row, data, index ) {
if (data[1] == 200) {
$('td', row).eq(1).addClass("highlithRow");
}
}
} );
} );
You can read more about it here: https://datatables.net/examples/advanced_init/row_callback.html
Upvotes: 1