Change Row background color based on cell value DataTable Change Row background color based on cell value DataTable jquery jquery

Change Row background color based on cell value DataTable


OK I was able to solve this myself:

$(document).ready(function() {  $('#tid_css').DataTable({    "iDisplayLength": 100,    "bFilter": false,    "aaSorting": [      [2, "desc"]    ],    "fnRowCallback": function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {      if (aData[2] == "5") {        $('td', nRow).css('background-color', 'Red');      } else if (aData[2] == "4") {        $('td', nRow).css('background-color', 'Orange');      }    }  });})


The equivalent syntax since DataTables 1.10+ is rowCallback

"rowCallback": function( row, data, index ) {    if ( data[2] == "5" )    {        $('td', row).css('background-color', 'Red');    }    else if ( data[2] == "4" )    {        $('td', row).css('background-color', 'Orange');    }}

One of the previous answers mentions createdRow. That may give similar results under some conditions, but it is not the same. For example, if you use draw() after updating a row's data, createdRow will not run. It only runs once. rowCallback will run again.


DataTables has functionality for this since v 1.10

https://datatables.net/reference/option/createdRow

Example:

$('#tid_css').DataTable({  // ...  "createdRow": function(row, data, dataIndex) {    if (data["column_index"] == "column_value") {      $(row).css("background-color", "Orange");      $(row).addClass("warning");    }  },  // ...});