Datatables: Change cell color based on values
I am using DataTable to create an interactive table. I have 9 columns, 5 of which are values. I want to change the background color of each cell based on their specific.
I have started off trying to change the entire row color first as this seemed like an easier task. However I can't get anything to change.
My code is below:
<head>
<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.13/css/jquery.dataTables.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.13/js/jquery.dataTables.js"></script>
<script>
$(document).ready(function(){
$('#countryTable').DataTable();
});
</script>
<script>
$(document).ready( function () {
$('#countryTable ').DataTable({
"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
if ( aData[3] > 11.7 )
{
$(nRow).css('color', 'red')
}
else if ( aData[2] == "4" )
{
$(nRow).css('color', 'green')
}
}
});
</script>
</head>
<body>
<table id ="countryTable" class="display" cellspacing="0" data-page-length='193'>
<thead>
<tr>
<th>Rank</th>
<th>Country</th>
<th>Code</th>
<th>Total</th>
<th>Beer</th>
<th>Wine</th>
<th>Spirits</th>
<th>Other</th>
<th>Score</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Estonia</td>
<td>EE</td>
<td>14.97</td>
<td>5.87</td>
<td>1.65</td>
<td>5.64</td>
<td>1.81</td>
<td>3 - Medium Risky</td>
</tr>
<tr>
<td>2</td>
<td>Belarus</td>
<td>BY</td>
<td>14.44</td>
<td>2.5</td>
<td>0.75</td>
<td>6.73</td>
<td>4.46</td>
<td>4 - Very Risky</td>
</tr>
</tbody>
I have also tried using the following function but to no luck. If anyone could help it would be greatly appriciataed as I am very to to java script.
$(document).ready( function () {
$('#countryTable').DataTable({
"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
if ( aData[3] == "5" )
{
$('td', nRow).css('background-color', 'Red');
}
else if ( aData[3] == "4" )
{
$('td', nRow).css('background-color', 'Orange');
}
}
});
First of all, initialize DataTable
only once. Then as per your question, use rowCallback
and not fnRowCallBack
as shown below:
var oTable = $('#countryTable').DataTable({
'rowCallback': function(row, data, index){
if(data[3]> 11.7){
$(row).find('td:eq(3)').css('color', 'red');
}
if(data[2].toUpperCase() == 'EE'){
$(row).find('td:eq(2)').css('color', 'blue');
}
}
});
Here's a fiddle