Ajax Datatable: changing row color based on the data

We have the following table which is populated with data, using Ajax

Now, let’s say you want to color the table rows, based on the second column status after, the table is already filled with data:

  • UNSTABLE -> Yellow
  • SUCCESS -> Green
  • Failure -> Red

For this, we will use the callback function ‘fnRowCallback‘ from datatable javascript.

It allows you to post modify each row in the table after, it’s already processed by the server, but before it displayed to the user. Exactly what we need in our case.

Let’s take a look at the code

$(document).ready( function() {
  $('#example').dataTable( {
    "fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
      if ( aData[1] == "FAILURE" )
      {
        $('td', nRow).css('background-color', '#f2dede' );
      }
      else if ( aData[1] == "SUCCESS" )
      {
        $('td', nRow).css('background-color', '#dff0d8');
      }
      else if ( aData[1] == "UNSTABLE" )
      {
        $('td', nRow).css('background-color', '#fcf8e3');
      }
      else
      {
        $('td', nRow).css('background-color', '#d9edf7');
      }
    }
  } );
} );

Let’s deep dive into the code. We are post modifying our table, with the id ‘example’. The only reason for the following two lines to change is if, your table’s id is not ‘example’ and then you would like to change it to your table’s id

$('#example').dataTable( {
    "fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {

Next, we are checking what our second column for each row includes. We are doing so by accessing aData list, where each index is the number of the column. In our case, the result is in the second column and since we are counting starting from 0, we are interested in aData[1]

if ( aData[1] == "FAILURE" )

If there is a match in one of the conditionals (either aData[1] is FAILURE, SUCESS or UNSTABLE) we are modifying the css of the entire row, by specifically changing the background color

$('td', nRow).css('background-color', '#f2dede' );

If it matches none of them, the default color (blue) will be used

 else
      {
        $('td', nRow).css('background-color', '#d9edf7');
      }

Note: if you defined a name for each column, you might need to use it instead of simply a number. So if the column result is called on your javascript ‘result_column’, you’ll use aData[‘result_column’] to access the status.

The result:

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s