Conditional Background
This code makes a table cell's background-color change based on the number within.
by Harsh Bhatnagar
HTML
<table class="content bordered" border="3" cellspacing="2" cellpadding="3" valign="top">
<tbody>
<tr>
<th class="stopGapTH" colspan="4">
Patient List
</th>
<th class="stopGapTH" colspan="99">
Clinical Adherence Information
</th>
</tr>
<tr height="30">
<th align="middle">
Patient Name
</th>
<th align="middle">
DOB
</th>
<th align="middle">
Primary Disease
</th>
<th align="middle">
Risk Index
</th>
<th>
Athsma
</th>
<th>
COPD
</th>
<th>
Diabetes
</th>
<th>
Heart Disease
</th>
</tr>
<tr>
<td>
Louis Armstrong
</td>
<td>
Blah
</td>
<td class="stopGapCondition"></td>
<td class="stopGapCondition"></td>
<td class="stopGapCondition">
50
</td>
<td class="stopGapCondition">
80
</td>
<td class="stopGapCondition">
75
</td>
<td class="stopGapCondition">
90
</td>
</tr>
<tr>
<td>
Bob Barker
</td>
<td>
Blah
</td>
<td class="stopGapCondition"></td>
<td class="stopGapCondition"></td>
<td class="stopGapCondition red">
49
</td>
<td class="stopGapCondition yellow">
50
</td>
<td class="stopGapCondition yellow">
89
</td>
<td class="stopGapCondition green">
90
</td>
</tr>
<tr>
<td>
David Brinkley
</td>
<td>
1Blah
</td>
<td class="stopGapCondition"></td>
<td class="stopGapCondition"></td>
<td class="stopGapCondition"></td>
<td class="stopGapCondition"></td>
<td class="stopGapCondition"></td>
<td class="stopGapCondition"></td>
</tr>
<tr>
<td>
Tom Brokaw
</td>
<td>
10Blah4
...
CSS
.high {
background-color: #f99;
}
.med {
background-color: #ff9;
}
.low {
background-color: #9f9;
}
.notApplicable {
background-color: #fff;
}
td.stopGapCondition {
text-align: center;
}
JavaScript
$('.stopGapCondition').each(function() {
var $this = $(this);
var value = $this.text();
if (!/^\s*\d+(\.\d+)?\s*$/.test(value)) {
$this.addClass('notApplicable');
return;
}
if (value < 50) {
$this.addClass('high');
} else if (value < 90) {
$this.addClass('med');
} else {
$this.addClass('low');
}
$this.text($this.text() + '%');
});