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

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

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 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

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

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: