Jesse Jesse - 2 months ago 6
HTML Question

How to incorporate javascript with HTML to make table change color depending on value?

How would I create a javascript that will change the color of the box depending on it's value?

<table>
<tr class="top row">
<th> Status </th>
<th> Name</th>
<th> StudentID </th>
<th> Grades </th>
</tr>
<tr>
<td> BAD </td>
<td> Jason </td>
<td> 955012 </td>
<td> 20 </td>
</tr>
</table>


eg; if box value (td) = OK box will be green, if value is BAD box will be yellow.

Current Java script based from similar question

$('#test [id^="available_"]').each(function(){

var closestTd = $(this).closest('td');
var valueCache = parseInt($(this).val());

if(valueCache === CRITICAL) {
closestTd .addClass('red');
}
else if(valueCache === BAD) {
closestTd.addClass('yellow');
}
else {
closestTd.addClass('green');
}

});

Answer

You need to use innerHTML to get value from td:

<table>
<tr class="top row">
    <th> Status </th>
    <th> Name</th>
    <th> StudentID </th>
    <th> Grades </th>
</tr>
<tr>
    <td id="td"> OK </td>
    <td> Jason </td>
    <td> 955012 </td>
    <td> 20 </td>
</tr>
</table>
<script>
   var td = document.getElementById('td');
   if(td.innerHTML == ' OK ')
      td.style.backgroundColor = 'green';
   else if(td.innerHTML == ' BAD ')
      td.style.backgroundColor = 'yellow';
</script>
Comments