简体   繁体   中英

Changing colour of a particular index in a table

A table has two rows and three columns. The requirement is that if the sum of second and third column for a particular row is not equal to 12 than the background colou for same row but first column will change to red.

Note: First column is having a text only. Second and third columnns have textboxes containing integer values.

Example:

<table>
    <tr>
      <td>A</td>
      <td>2</td>
      <td>13</td>
    </tr>
    <tr>
      <td>B</td>
      <td>2</td>
      <td>10</td>
    </tr>
    <tr>
      <td>C</td>
      <td>2</td>
      <td>14</td>
    </tr>
</table>

In the above example, the sum 2+13 and 2+14 are greater than 12, so the background colour of first for both of them should change to red colour.

You can simply do:

$('tr').each(function(i, row) {
    // init sum for each new parsed row
    var sum = 0;
    // parse row children ('td')
    $(this).children('td').each(function(j, col) {
        if (j > 0) {
            // sum all columns, except first
            sum += parseInt($(col).text());
        }
    });
    // check sum
    if (sum != 12) {
        // Change background here for first column of current row
        $(row).find('td').first().css({
            backgroundColor: 'red'
        });
    }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM