11

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

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

1 Answer 1

18

Update. The original answer were targeting dataTables 1.9.x. It still works, and works with dataTables 1.10.x as well (so far) but here is a pure dataTables 1.10.x version :

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/


You should use the fnRowCallback event for this. From the docs :

This function allows you to 'post process' each row after it have been generated for each table draw, but before it is rendered on screen. This function might be used for setting the row class name etc.

So in your case, do this :

$("#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 it in action in this jsfiddle -> http://jsfiddle.net/GfNeA/

Sign up to request clarification or add additional context in comments.

1 Comment

When setting by options in the current version, we have also createdRow, which can often be more efficient). Links for both options: datatables.net/reference/option/createdRow datatables.net/reference/option/rowCallback

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.