tags:

views:

473

answers:

3

I have number of rows like

<'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 colour 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.?

A: 

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 ...
});
Chris Pebble
This will always make it green since all values are less than 100
codemeit
+3  A: 

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');
TM
That's a very elegant solution. :)
Helephant
This requires some logic on the names of the element classes though.
codemeit
@codemeit no it doesn't rely on the class at all. The selector can simply check the contents of the tag, or do anything else you are allowed to do in javascript.
TM
oh right. excellent.
codemeit
A: 

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>
codemeit