Conditionally set column text color
Conditionally set column text color
chreHIukCI
Posts: 4Questions: 0Answers: 0
I have a simple table that has a column of numbers. If the number is negative I want the color to be red. I've found examples of how to make the whole ROW red, but I only want to set the color of the text in the cell to red. I'm new to DataTables and I'm guessing this is simple, but I can't figure out how to do it.
This discussion has been closed.
Replies
HTML Page:
[code]
"aoColumns": [
null,
null,
{ "fnRender": function(obj) {
var cellValue = obj.aData[ obj.iDataColumn ];
if (cellValue && cellValue <= 0) {
return "" + cellValue + "";
} else {
return cellValue;
}
}
}
]
[/code]
CSS:
[code]
.redText { color: red; }
[/code]
Another solution to avoid these issues is to use a CSS class on the cell (rather than text within the cell) to change colors. To use this approach you would need to get the cell (there are api functions like fnGetNodes() ) and apply the CSS class (i.e. use JQuery's addClass() ). For this approach, other callbacks, or iterating using JQuery might make it easier or more appropriate since fnRender expects you to return (and often modify) a string that ends up in the cell, and doesn't give you the cell (the TD cell is not yet created, or at least not added to the DOM yet).
I like the challenge presented in changing the cell's formatting and keeping the cell's contents "clean" (for lack of a better word). I'm going to work on an implementation and will update this post when I have one. I'm new to jQuery, so it might be awhile :-).
[code]
"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
/* numbers less than or equal to 0 should be in red text */
if ( parseFloat(aData[4]) <= 0 ) {
jQuery('td:eq(4)', nRow).addClass('redText');
}
return nRow;
},
[/code]
This adds the 'redText' class to the cell rather than to the data within the cell. This is working great and I don't have to worry about setting bUseRendered. Thank you again for your reply.