Jackson
Jackson

Reputation: 6851

Conditionally change background color of table cell

I have a table with many rows. In each row there is a cell with an id of 'overwrite'. If overwrite contains a number > 0 than I would like to change the background color of the cell to red.

I have javascript that looks like this:

$('#overwrite').each(function() {
    if (parseInt($(this).text()) > 0) {
        $(this).addClass('records_overwritten');
    }
});

This only changes the background color of one cell, and none of the others even though they also contain a value greater than 0. I am a bit confused what the issue is.

Here is an example of a table row:

<tr>
  <td>March 18, 2014</td>
  <td>John Smith</td>
  <td>5</td>
  <td>10</td>
  <td id="overwrite">1</td>
  <td>56</td>
</tr>

Upvotes: 0

Views: 3411

Answers (4)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123387

Since an ID must be unique on a page — and $('#overwrite') would return at most one element — use a class instead of repeated ID's

$('.overwrite').each(function() {
    if (parseInt($(this).text(), 10) > 0) {
        $(this).addClass('records_overwritten');
    }
});

Furthermore, if the column to check is always the 5th <td> of every row, you may also avoid to insert unnecessary attributes and you can retrieve those elements with $('tr td:nth-child(5)');

Also note that parseInt requires a radix as a second argument

Upvotes: 1

gramgram
gramgram

Reputation: 565

ID is intented to be unique on page, so $('#ID').each is not a good idea. Maybe you could use class or attr value for identification.

About the background setting: closest() is a good solution here.

$( ".overwrite" ).closest( "tr" ).css( "background-color", "red" );

Upvotes: 0

andrew
andrew

Reputation: 9583

change the id to class

 <tr>
  <td>March 18, 2014</td>
  <td>John Smith</td>
  <td>5</td>
  <td>10</td>
  <td class="overwrite">1</td>
  <td>56</td>
 </tr>

and use class selector instead

 $('.overwrite').each(function() {.....

Upvotes: 1

steven
steven

Reputation: 646

The id attribute is assumed to be unique to a page, and so jQuery still stop looking after it finds one. You could get around this by using the following selector [id="overwrite"] but you really should be using classes or something.

Upvotes: 0

Related Questions