0
votes

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>
4
You can only use one ID value in a document.Dissident Rage
an id should be uniqueandrew
the issue is the duplicate IDslshettyl

4 Answers

1
votes

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

1
votes

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() {.....
0
votes

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.

0
votes

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" );