简体   繁体   中英

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 : 在此处输入图片说明

Example test result i have run :

  • Below 10 and Above Minimum = Unchanged
  • 10 and Above = Red << it should be Unchanged, because it is above minimum
  • 50 and Above = Unchanged

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

Thanks for your help!

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/

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");
        }
}

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;
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM