Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Table Colour 2

Status
Not open for further replies.

pancake

Programmer
Aug 21, 2001
88
GB
I have a table that I want to change the font colour or cell colour depending upon the value

e.g. if I have a value of 3 in the table, the font will be green, a value of 5 makes the font (of that value only) go red.

Any suggestions most welcome.

Thanks in advance.
 
Hi

Yes. I suggest to give us more details. For example why would JavaScript be involved in styling a [tt]table[/tt] ?

But anyway, for example this works for all [tt]table[/tt]s on the page, when the page is loaded :
Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "[URL unfurl="true"]http://www.w3.org/TR/html4/strict.dtd">[/URL]
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title></title>
<script type="text/javascript">
function colortable()
{
  var tab=document.getElementsByTagName('table')
  for (var i=0;i<tab.length;i++) {
    for (var j=0;j<tab[i].rows.length;j++) {
      for (var e=0;e<tab[i].rows[j].cells.length;e++) {
        switch (parseInt(tab[i].rows[j].cells[e].innerHTML)) {
          case 3:tab[i].rows[j].cells[e].style.color='green'; break;
          case 5:tab[i].rows[j].cells[e].style.color='red'; break;
        }
      }
    }
  }
}
window.onload=colortable
</script>
</head>
<body>
<table>
<tr><td>1</td><td>2</td><td>3</td></tr>
<tr><td>4</td><td>5</td><td>6</td></tr>
</table>
<table>
<tr><td>1</td><td>2</td></tr>
<tr><td>3</td><td>4</td></tr>
<tr><td>5</td><td>6</td></tr>
</table>
</body>
</html>

Feherke.
 
Is this table being generated dynamically on the server-side? If so, I recommend assigning css classes to the cells as you are building the table. Otherwise:
Code:
<table id="mytable" style="background-color:gray">
  <tr>
    <td>5</td>
    <td>4</td>
    <td>1</td>
  </tr>
  <tr>
    <td>2</td>
    <td>3</td>
    <td>5</td>
  </tr>
</table>

<script>
window.onload = colorCells;

function colorCells(){
  var tds = document.getElementById("mytable").getElementsByTagName("TD");
  for(var i=0; i<tds.length; i++){
    switch(tds[i].innerText.trim()){
      case "1": tds[i].style.color = "green"; break;
      case "2": tds[i].style.color = "lime"; break;
      case "3": tds[i].style.color = "yellow"; break;
      case "4": tds[i].style.color = "orange"; break;
      case "5": tds[i].style.color = "red"; break;
    }
  }
}

String.prototype.trim = function(){ return this.replace(/^\s+|\s+$/g,''); }
</script>

Adam
 
Thanks to both of you that is just what I was looking for.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top