42

I am using DataTable plugin to display some records. I have 3 rows, Name, Date, Amount. I want the background color of the row to change based on specific values in the amount column.

This is my code:

<script type="text/javascript" charset="utf-8">
  $(document).ready(function() {
    var table = $('#tid_css').DataTable({
      'iDisplayLength': 100,
      "bFilter": false,
      "aaSorting": [
        [2, "desc"]
      ]
    });
  });
</script>

As a test, I added below code alongside above code but getting below error

"DataTables warning: table id=tid_css - Cannot reinitialise DataTable"

<script type="text/javascript" charset="utf-8">
  $(document).ready(function() {
    $('#tid_css').dataTable({
      "fnRowCallback": function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
        if (aData[2] == "1") {
          $('td:eq(2)', nRow).html('<b>1</b>');
        }
      }
    });
  });
</script>

How easy can I do this using fnRowCallback with different conditions like if amount is 1 then color is Red, 2 = Blue, 3 = Blue etc.

Narendra Jadhav
  • 10,052
  • 15
  • 33
  • 44
Chelseawillrecover
  • 2,596
  • 1
  • 31
  • 51

9 Answers9

68

OK I was able to solve this myself:

$(document).ready(function() {
  $('#tid_css').DataTable({
    "iDisplayLength": 100,
    "bFilter": false,
    "aaSorting": [
      [2, "desc"]
    ],
    "fnRowCallback": function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
      if (aData[2] == "5") {
        $('td', nRow).css('background-color', 'Red');
      } else if (aData[2] == "4") {
        $('td', nRow).css('background-color', 'Orange');
      }
    }
  });
})
Narendra Jadhav
  • 10,052
  • 15
  • 33
  • 44
Chelseawillrecover
  • 2,596
  • 1
  • 31
  • 51
  • 1
    Do you know how can this work in a dynamic way, meaning... instead of using an specific index, obtain the index of an specific column header aData[?] – Jimmy Oct 10 '14 at 20:09
  • 1
    @Jimmy you can get the index with MyTable.column("#status").index(), provided that you have assigned ID's to the columns in your HTML. –  Nov 18 '14 at 07:55
  • 7
    This solution didn't work for me. However, I found this solution in Datatables Forum, and worked like a charm (Perhaps the OP has/had an older version of datatables)... https://datatables.net/forums/discussion/29717/change-row-background-color-depending-on-value-in-certain-cell#Comment_79736 – Theo Orphanos Jul 14 '16 at 18:52
  • 1
    This answer will set all `td` color in a row this is not an efficient way. – Aravindh Gopi May 15 '17 at 08:14
  • is there any example on how we parseINT in this if else statement? – Amirul Asyraf Mar 28 '22 at 04:57
33

The equivalent syntax since DataTables 1.10+ is rowCallback

"rowCallback": function( row, data, index ) {
    if ( data[2] == "5" )
    {
        $('td', row).css('background-color', 'Red');
    }
    else if ( data[2] == "4" )
    {
        $('td', row).css('background-color', 'Orange');
    }
}

One of the previous answers mentions createdRow. That may give similar results under some conditions, but it is not the same. For example, if you use draw() after updating a row's data, createdRow will not run. It only runs once. rowCallback will run again.

devlin carnate
  • 8,309
  • 7
  • 48
  • 82
16

DataTables has functionality for this since v 1.10

https://datatables.net/reference/option/createdRow

Example:

$('#tid_css').DataTable({
  // ...
  "createdRow": function(row, data, dataIndex) {
    if (data["column_index"] == "column_value") {
      $(row).css("background-color", "Orange");
      $(row).addClass("warning");
    }
  },
  // ...
});
Narendra Jadhav
  • 10,052
  • 15
  • 33
  • 44
gArn
  • 421
  • 3
  • 9
  • 2
    Actually, the functionality for v 1.10 is [rowCallback](https://datatables.net/reference/option/rowCallback). createdRow may give you the same effect in certain cases, but it is not the same. – devlin carnate Mar 08 '17 at 19:48
  • This worked perfectly! Thank you! I've been trying to fix this all morning long! – Carthax Apr 30 '20 at 16:39
10

Since datatables v1.10.18, you should specify the column key instead of index, it should be like this:

rowCallback: function(row, data, index){
    if(data["column_key"] == "ValueHere"){
        $('td', row).css('background-color', 'blue');
    }
}
Norielle Cruz
  • 170
  • 5
  • 14
4

This is how managed to change my data table row background (DataTables 1.10.19)

$('#memberList').DataTable({
    "processing": true,
    "serverSide": true,
    "pageLength":25,
    "ajax":{
        "dataType": "json",
        "type": "POST",
        "url": mainUrl+"/getMember",
       },
    "columns": [
        { "data": "id" },
        { "data": "name" },
        { "data": "email" },
        { "data": "phone" },
        { "data": "country_id" },
        { "data": "created_at" },
        { "data": "action" },
    ],
    "fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
        switch(aData['country_id']){
            case 1:
                $('td', nRow).css('background-color', '#dacfcf')
                break;
        }
    }
});

You can use fnRowCallback method function to change the background.

Bhanu Sengar
  • 372
  • 2
  • 10
3

I used createdRow Function and solved my problem

    $('#result1').DataTable( {
        data: data['firstQuery'],
        columns: [
                        { title: 'Shipping Agent Code' },
                        { title: 'City' },
                        { title: 'Delivery Zone' },
                        { title: 'Total Slots Open ' },
                        { title: 'Slots Utilized' },
                        { title: 'Utilization %' },

                    ],
                    "columnDefs": [
                        {"className": "dt-center", "targets": "_all"}
                      ],
                      "createdRow": function( row, data, dataIndex){
                            if( data[5] >= 90  ){
                                $(row).css('background-color', '#F39B9B');
                            }
                            else if( data[5] <= 70  ){
                                $(row).css('background-color', '#A497E5');
                            }
                            else{
                                $(row).css('background-color', '#9EF395');
                            }

                        }
                } );
Arpit Singh
  • 398
  • 4
  • 11
1

I needed it with the index name and this is what worked for me using v. 1.11.3:

"createdRow": function( row, data, dataIndex ) {
    if ( data['my_column_name'] == 1 ) {
        $(row).addClass( 'bg-warning' );
    }
},
Luis Rodriguez
  • 355
  • 3
  • 7
0

I Used rowCallBack datatable property it is working fine. PFB :-

"rowCallback": function (row, data, index) {

                        if ((data[colmindx] == 'colm_value')) { 
                            $(row).addClass('OwnClassName');
                        }
                        else if ((data[colmindx] == 'colm_value')) {
                                $(row).addClass('OwnClassStyle');
                            }
                    }
satya prakash
  • 87
  • 1
  • 5
0

Callback for whenever a TR element is created for the table's body.

$('#example').dataTable( {
      "createdRow": function( row, data, dataIndex ) {
        if ( data[4] == "A" ) {
          $(row).addClass( 'important' );
        }
      }
    } );

https://datatables.net/reference/option/createdRow