MHS MHS - 9 days ago 8
HTML Question

How to change the background color of negative value in a cell?

I have a table with some numbers in it at different cells.

I want to check if any of the cell has a

value < 0
, it may change its row's background color to red!
I want function to be called on a button click, and it may check entire document's tables.
This is what I am using:

function checkNegative(){
function(e) {
var $target = $(e.target);
var checkNeg = function(c) {
for(var i=0,$ci; i<c.length; i++) {
$ci = $(c[i]);
if(parseInt($ci.text()) < 0) $ci.css("color", "red");
else $ci.css("color", "black");
}
};
checkNeg($target.parents("table").find("[td]"));
}
}


I found this over Internet, but not working for my case!
Please help!
My Table looks like this:

<table border="1" bordercolor="#bababb">
<thead>
<tr>
<th>NUMBER1</th>
<th>NUMBER2</th>
<th>NUMBER3</th>
<th>NUMBER4</th>
</tr>
</thead>
<tbody>
<tr>
<td>1202</td>
<td>2587</td>
<td>-2541</td>
<td>3652</td>
</tr>
<tr>
<td>1202</td>
<td>2587</td>
<td>2541</td>
<td>-3652</td>
</tr>
<tr>
<td>1202</td>
<td>-2587</td>
<td>2541</td>
<td>3652</td>
</tr>
<tr>
<td>-1202</td>
<td>2587</td>
<td>2541</td>
<td>3652</td>
</tr>
<tr>
<td>-1202</td>
<td>2587</td>
<td>-2541</td>
<td>3652</td>
</tr>
<tr>
<td>1202</td>
<td>-2587</td>
<td>-2541</td>
<td>3652</td>
</tr>
</tbody>
</table>

Answer

I guess I've a solution for the problem. I assume a table with 6 rows and 4 columns with positive and negative values.

I also have a javascript method which does the colouring of the background depending on positive or negative values. Please find the fiddle here

The script is:

var formatBackground=function(){
    var table, tbody, rowCount, cellCount, value;
    table=document.getElementsByTagName('table')[0];
    if(table.childNodes[1]) tbody=table.childNodes[1];
    if(tbody) rowCount=tbody.childNodes.length;

    for(i=0;i<rowCount;i++){
        cellCount=tbody.childNodes[i].childNodes.length;

        for(j=1;j<cellCount;j++){
            value=tbody.childNodes[i].childNodes[j].outerText;
            if(parseInt(value)<0) tbody.childNodes[i].childNodes[j].setAttribute('style','background-color: #f00');
            j+=1;
        }
        i+=1;
    }
};