Forum Moderators: open

Message Too Old, No Replies

Changing Cell Background colour, depending on the cell content.

         

Balakir

1:11 pm on May 12, 2010 (gmt 0)

10+ Year Member



Hi All,

I am looking to change the background colour of cells depending on the content.

At the moment each cell has either 1 or 0 as the content. I would like the background colour to be set to green if it is 1 and red if it is 0 as well as the content actually being removed.

I have been googling for a while and trying various things but so far I cannot get this to work.

I know I can use document.getElementById('tablename').rows.length to get the number of rows which allows the for loop to check each row. What I do not understand is how I would go about checking each cell.

Any help greatly appreciated.

Bala

birdbrain

7:09 pm on May 12, 2010 (gmt 0)



Hi there Balakir,

try this example, it may suit your requirements...


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="language" content="english">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">

<title></title>

<style type="text/css">
#mytable {
border:1px solid #999;
margin:auto;
}
#mytable td {
width:30px;
height:30px;
border:1px solid #666;
text-align:center;
}
.green {
background-color:#f00;
}
.red {
background-color:#0f0;
}
</style>

<script type="text/javascript">

function setTdBackground(){
cells=document.getElementById('mytable').getElementsByTagName('td');
for(c=0;c<cells.length;c++) {
if(cells[c].firstChild.nodeValue==1 ){
cells[c].className='green';
}
else {
if(cells[c].firstChild.nodeValue==0){
cells[c].className='red';
cells[c].firstChild.nodeValue='';
}
}
}
}

if(window.addEventListener){
window.addEventListener('load',setTdBackground,false);
}
else {
if(window.attachEvent){
window.attachEvent('onload',setTdBackground);
}
}
</script>

</head>
<body>

<table id="mytable"><tr>
<td>0</td><td>1</td><td>1</td><td>0</td>
</tr><tr>
<td>1</td><td>0</td><td>1</td><td>0</td>
</tr><tr>
<td>1</td><td>0</td><td>0</td><td>0</td>
</tr><tr>
<td>0</td><td>1</td><td>0</td><td>1</td>
</tr></table>

</body>
</html>


birdbrain

Balakir

7:48 am on May 13, 2010 (gmt 0)

10+ Year Member



Thanks birdbrain :) that done the trick and I now know how to get to get td content :)

birdbrain

8:04 am on May 13, 2010 (gmt 0)



No problem, you're very welcome. ;)