views:

30

answers:

1

I have an HTML table that is similar to this simplified example:

<table>
  <tbody>
    <tr><th>Player</th><th>Score</th></tr>
    <tr><td>Jack</td><td>7</td></tr>
    <tr><td class="parent">Green Team</td><td></td></tr>
    <tr><td class="child">Mark</td><td>11</td></tr>
    <tr><td class="child">Tom</td><td>5</td></tr>
    <tr><td>Steven</td><td>8</td></tr>
    <tr><td>Greg</td><td>4</td></tr>
    <tr><td class="parent">Blue Team</td><td></td></tr>
    <tr><td class="child">Joe</td><td>10</td></tr>
    <tr><td class="child">Jill</td><td>12</td></tr>
    <tr><td class="child">Rachel</td><td>9</td></tr>
  </tbody>
</table>

I am trying to code the necessary jQuery to iterate through all child rows of a parent, sum the scores, and insert the sum to the parent's score cell. The rows that are not associated with a parent should be skipped/ignored.

After the jQuery code executes, the above table should be transformed into this:

<table>
  <tbody>
    <tr><th>Player</th><th>Score</th></tr>
    <tr><td>Jack</td><td>7</td></tr>
    <tr><td class="parent">Green Team</td><td>16</td></tr>
    <tr><td class="child">Mark</td><td>11</td></tr>
    <tr><td class="child">Tom</td><td>5</td></tr>
    <tr><td>Steven</td><td>8</td></tr>
    <tr><td>Greg</td><td>4</td></tr>
    <tr><td class="parent">Blue Team</td><td>31</td></tr>
    <tr><td class="child">Joe</td><td>10</td></tr>
    <tr><td class="child">Jill</td><td>12</td></tr>
    <tr><td class="child">Rachel</td><td>9</td></tr>
  </tbody>
</table>

I'm not sure the best way to solve this. Any ideas?

+2  A: 

You can do something like this:

$("tr:has(td.parent)").each(function() {
  var sum = 0;
  $(this).nextUntil(':not(:has(td.child))').children(':nth-child(2)').each(function() {
    sum += parseInt(this.innerHTML, 10);
  });
  $(this).children(':eq(1)').text(sum);
});

You can give it a try here, this takes each <tr> that contains <td class="parent"> and goes with .nextUntil() until it finds a row without a <td class="child">. For those rows it loops through the second cell (:nth-child(2)) and adds the value to the sum. ​

Nick Craver
+1, especially for including the second argument to parseInt.
Ken Redler
Beautiful, thank you!
richard23