efraim
efraim

Reputation: 77

Datatable change a row color with rowcallback

I am using datatables and currently stuck in changing a row to another color if a STATEMENT meet the requirement, already tried many things but it has really weird error, my codes are :

"rowCallback": function( row, data, index ) {
        if ( data[2] < data[4] ) {
          $('td', row).css('background-color', 'pink');
        }
}

While in my response file, i wrote this query :

$sql = "SELECT itemid,itemname,stock,unit,minimum FROM item WHERE type LIKE 'homecare'";

I want to change the row color if the item's stock is LOWER than the minimum value set by the user.

My current datatable test results are : enter image description here

Example test result i have run :

While the database settings for both row 'minimum' column are the same number (5)

Thanks for your help!

Upvotes: 4

Views: 24371

Answers (3)

Bhanu Sengar
Bhanu Sengar

Reputation: 382

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

"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
        switch(aData['country_id']){
            case 1:
                $('td', nRow).css('background-color', '#dacfcf')
                break;
        }
    }

Upvotes: 0

Sracanis
Sracanis

Reputation: 490

New Datatable has the following feature for highlighting the row:

"rowCallback": function( row, data, index ) {
        if ( data[2] < data[4] ) {
          //Highlight the cell value
          $(row).find('td:eq(2)').css('color', 'red');
          //Highlight the row
          $(row).addClass("danger");
        }
}

Upvotes: 4

davidkonrad
davidkonrad

Reputation: 85558

You seem to have 9 cc, 10 cc and so as values in the stock column? If you want numerical comparison you must extract the number for each column as number. I would also add a .pink class to the <tr>, instead of setting background-color on all <td>'s.

"rowCallback": function( row, data, index ) {
  var stock = parseFloat(data[0]), //data[2]
      minimum = parseFloat(data[1]), //data[4]
      $node = this.api().row(row).nodes().to$();

  if (stock < minimum ) {
     $node.addClass('pink')
  } 
}      

demo -> http://jsfiddle.net/104o96cn/

Upvotes: 4

Related Questions