Sometimes you would like to change the text color in a row (or cell) based on text already in the table. Luckily the dataTables plugin allows you to do this using their fnDrawCallback callback function. I am sure that there is a better way to this, but I couldn’t find an easy solution so here’s what I came up. I hope it helps someone…
How To Change the Text Color Dynamically
We are simply going to add a CSS class to get the effect we want. You can easily make any CSS changes you want to change the effect on the Row. First let’s create the classes that we will be using.
.statusBlack { color: black; } .statusRed { color: red; } .statusBlue { color: blue; } .statusGreen { color: green; }
Pretty simple, now let’s create the table with it’s headers. The data for this table will be brought in via MySQL. (hack if you want, there’s nothing here except this data)
<table id="statusTable" class="display"> <thead> <tr> <th>ID</th> <th>Status</th> <th>Name</th> <th>Description</th> </tr> </thead> <tbody></tbody> </table>
Using dataTables we will bring all the data in with the following code.
sTable = $('#statusTable').dataTable( { "bProcessing": true, "bServerSide": true, "sAjaxSource": "deep.php", "fnDrawCallback": function( oSettings ) { for ( var i=0, iLen=oSettings.aoData.length ; i<iLen ; i++ ) { var status = oSettings.aoData[i]._aData[1]; var colorCSS; if(status === 'Open') { colorCSS = 'statusGreen'; } else if(status === 'In Progress') { colorCSS = 'statusBlue'; } else if(status === 'Closed') { colorCSS = 'statusRed'; } else { colorCSS = 'statusBlack'; } oSettings.aoData[i].nTr.className += " "+colorCSS; } }, "bAutoWidth": true });
You’ll notice that the fnDrawCallback callback function is in there. Here’s an explanation of what’s happening.
We are first passing oSettings into the function and using it to loop through the rows, where i is the current row. Using aoData[i]._aData[1] we can get the value of the data in the second cell of the row, which is our Status.
Finally we use aoData[i].nTr.className to add the appropriate class name to the row.
If you missed it above, check out a demo of it Changing Row Colors ( text or background ) with the dataTables plugin for jQuery
Jim Gaudet - Changing Text Color or Background Color with the DataTables jQuery Plugin