How to apply conditional formatting with datatables.js?

I have an html table that uses datatables.js and could not find a clear example of how to apply conditional formatting.

How can I change the text color of a cell in column 4 when its value == 0 and the value in column 5 is! = 0

<script> $(document).ready(function () { $("#GeneratedData").dataTable({ "sDom": 'T<"clear">lrtip', "oTableTools": { "sSwfPath": "http://localhost:5637/Content/swf/copy_csv_xls_pdf.swf" }, "sPaginationType": "full_numbers" }); }) </script> 
+7
jquery datatables
source share
1 answer

Update . The initial answer was targeted at dataTables 1.9.x. It still works and works with dataTables 1.10.x (for now), but here is a clean version of dataTables 1.10.x:

 var table = $('#example').DataTable({ rowCallback: function(row, data, index) { if (data[3]=='0' && data[4]!='0') { $(row).find('td:eq(3)').addClass('color') } } }) 

demo β†’ http://jsfiddle.net/2chjxduy/


For this you should use fnRowCallback . From the docs:

This function allows you to "send" each row after it has been generated for each draw of the table, but before it is displayed on the screen. This function can be used to set the class name of a string, etc.

So in your case do the following:

 $("#GeneratedData").dataTable({ //your settings as above here fnRowCallback: function(nRow, aData, iDisplayIndex, iDisplayIndexFull) { if ($(nRow).find('td:eq(3)').text()=='0' && $(nRow).find('td:eq(4)').text()!='0') { $(nRow).find('td:eq(3)').addClass('color'); } } }); 

color is a predefined CSS class. See this in action in this jsfiddle -> http://jsfiddle.net/GfNeA/

+11
source share

All Articles