Andrew Jackson
Andrew Jackson

Reputation: 11

Change text color in a table cell (if, else)

If have a table like this..

<table>
<tr>
<td class="cell1">20</td>
</tr>
</table>

and so one..with more than one <td> of course..

Now i would like to change the color of the text in the <td> if the number is smaler than 5.

Is that possible with jQuery?

There is no input-field or paragraph in <td>, just text.

Upvotes: 0

Views: 7417

Answers (4)

Adam
Adam

Reputation: 44939

Yes. You can use .each to loop through all the table cells. You can then get the text in the cell and parse it as an integer (base 10). If it is less than 5 you can change the css color to be whatever you want.

I'm assuming that all the numbers are integers and that they do not change after the page is loaded.

For example:

$("td").each(function(){
   $cell = $(this);
   if(parseInt($cell.text(),10) < 5){
      $cell.css("color", "red");
   }
});​

Try it!

Upvotes: 0

Akarun
Akarun

Reputation: 3350

You can test the content of the field like this:

$('.cell1').each(function() {
    if($(this).text() < 5) { 
        $(this).css('color', 'red');
    }
});

Upvotes: 0

Tim Withers
Tim Withers

Reputation: 12059

This should work:

$("table.myTable td").each(function(){
    if(parseInt($(this).html())<5){
        $(this).addClass("newColor");
    }
});

Upvotes: 0

Andreas Wong
Andreas Wong

Reputation: 60536

$('.cell1').each(function(i, n) {
   if($(n).text() < 5) $(n).css('color', 'green');
});

Iterate through each cell, check value, then change accordingly

http://jsfiddle.net/bQfb6/2/

Upvotes: 3

Related Questions