I have a number of rows like this:
<tr>
<TD class="Lo">90%</TD>
<TD class="Poor">80%</TD>
<TD class="Lo">89%</TD>
<TD class="Mid">85%</TD>
<TD class="Poor">85%</TD>
<TD class="Mid">85%</TD>
<TD class="Hi">85%</TD>
</tr>
Now I want to access any elements in this row and set the color of that row based on values:
- If the 80% < value <= 85% colours yellow,
- If the 90% < value <= 95% colours red,
- If the 95% < value <= 100% colours green.
How to do this using jQuery?
-
It'd be good to provide the html with <table /> as well since table may have an id that can be used as a selector for intended highlighting.Ray Lu– Ray Lu2009年02月27日 14:05:37 +00:00Commented Feb 27, 2009 at 14:05
-
It's been a few days, how about choosing one of the answers?TM.– TM.2009年03月02日 17:47:50 +00:00Commented Mar 2, 2009 at 17:47
3 Answers 3
You might get some good use out of making a few custom selectors for this.
For example, here's one called "high":
jQuery.expr[':'].high = '(put your boolean logic here, inside quotes)';
Then, after you have your custom selectors, do this for each one:
$('td:high').css('color', 'green');
3 Comments
Try something like this
$("td").each(function() {
if ($(this).text().replace('%') <= 90) {
$(this).css('background','red');
} else if ($(this).text().replace('%') <= 100) {
$(this).css('background','green');
}
// repeat ...
});
1 Comment
Here is a working solution and the highlight logic done at client side.
Given html table with id="stats" which means the highlights will be applied for this table's td.
<table id="stats">
<tr>
<td>83%</td>
<td>96%</td>
<td>92%</td>
</tr>
<tr>
<td>100%</td>
<td>94%</td>
<td>85%</td>
</tr>
</table>
Javascript with JQuery to perform the highlights.
<script type="text/javascript">
$(window).ready(function() {
// for each td element within elements whose id="stats"
$("#stats td").each(function() {
// current td element
var td = $(this);
// do it once only
var val = td.text().replace('%', '');
td.css('background', val > 80 && val <= 85 ? 'yellow'
: val > 90 && val <= 95 ? 'red'
: val > 95 && val <= 100 ? 'green'
: 'black'); // black is default
});
});
</script>