formatting cells in the tables based on the cell value
formatting cells in the tables based on the cell value
I am new to datatables so excuse me if my question is too simple.
I am working off this question that was posted here
I am using this example to achieve what I want, which is if the cell value is above 80 I want a red back ground, if its below 80 I wan ta green back ground.
here is my code
'createdRow': function ( row, data, index ) {
//$(row).addClass('highlight');
//if ( data['sitecode'].replace(/[\$,]/g, '') * 1 > 150000 ) {
// $('td', row).eq(4).addClass('highlight');
//}
if ( parseInt(data['counter1'].substring(0,2)) >= 80 ) {
$('td', row).eq(1).css("background","red");
}
if ( parseInt(data['counter1'].substring(0,2)) < 80 ) {
$('td', row).eq(1).css("background","green");
}
if ( parseInt(data['counter2'].substring(0,2)) >= 80 ) {
$('td', row).eq(2).css("background","red");
}
if ( parseInt(data['counter2'].substring(0,2)) < 80 ) {
$('td', row).eq(2).css("background","green");
}
}
my data looks like this
DeviceName,counter1,counter2,counter3,counter4
DeviceName1,85%,10%,51%,63%
DeviceName2,85%,85%,74%,70%
DeviceName3,80%,81%,70%,66%
DeviceName4,78%,82%,70%,74%
DeviceName5,77%,75%,68%,58%
DeviceName6,77%,72%,66%,58%
Note this only works on the 1st 2 column counters, and the code is very verbose. Can anyone offer a better solution on doing this?
This question has an accepted answers - jump to answer
Answers
counterIndexCount
to be the number of "counterX" fields you've got.<td>
s to be green:table#myDataTable tr td { background: green }
.highlightClassName
, write CSS for it to change the background color like this:.highlight { background: red }
.tks, thats a good start for me. It does't change the color to red, everything is just showing as green. even the DeviceName column.
Edit1
table#counterTableDomId .highlight { background: red }
this makes the cells go red. Don't want the DeviceName column. to go green though.Also, is there a way to write this
data['counter'+ i]
more generically, so that it would work on a variable number of columns.As long as the columns are always named "counter" followed by an integer, simply changing
counterIndexCount
to the number of columns you expect will work.If you don't know the number of columns to expect, or the names of the columns, AND you don't have to support old browsers, you can use
data.keys()
to get the column names and setcounterIndexCount = data.keys().length
.If you have to support old browsers, you can use
jQuery.map()
(documentation) to loop through the keys instead of thefor
loop.