Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Row background color based on cell value DataTable

I am using DataTable plugin to display some records. I have 3 rows, Name, Date, Amount. I want the background color of the row to change based on specific values in the amount column.

This is my code:

<script type="text/javascript" charset="utf-8">
  $(document).ready(function() {
    var table = $('#tid_css').DataTable({
      'iDisplayLength': 100,
      "bFilter": false,
      "aaSorting": [
        [2, "desc"]
      ]
    });
  });
</script>

As a test, I added below code alongside above code but getting below error

"DataTables warning: table id=tid_css - Cannot reinitialise DataTable"

<script type="text/javascript" charset="utf-8">
  $(document).ready(function() {
    $('#tid_css').dataTable({
      "fnRowCallback": function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
        if (aData[2] == "1") {
          $('td:eq(2)', nRow).html('<b>1</b>');
        }
      }
    });
  });
</script>

How easy can I do this using fnRowCallback with different conditions like if amount is 1 then color is Red, 2 = Blue, 3 = Blue etc.

like image 721
Chelseawillrecover Avatar asked Aug 07 '14 15:08

Chelseawillrecover


2 Answers

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');
      }
    }
  });
})
like image 166
Chelseawillrecover Avatar answered Nov 07 '22 12:11

Chelseawillrecover


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.

like image 33
devlin carnate Avatar answered Nov 07 '22 11:11

devlin carnate