roger rover
roger rover

Reputation: 641

jquery sum values of checkbox and place in adjacent td

How can I say in jQuery -

Sum the "value" of all checkboxes within each div.checkboxes and put the summed value to the next ?

<td>
   <div class=checkboxes>
      <LABEL style="white-space: nowrap;">
      <INPUT type="checkbox" name="user_registered" class="checkbox1" value="14"    >
      </LABEL><BR>                  
      <LABEL style="white-space: nowrap;">
      <INPUT type="checkbox" name="user_registered" class="checkbox2"  value="12"   >
   </div>
</td>
<td>
   <td> </td>


<td>
   <div class=checkboxes>
      <LABEL style="white-space: nowrap;">
      <INPUT type="checkbox" name="user_registered" class="checkbox1" value="24"    >
      </LABEL><BR>                  
      <LABEL style="white-space: nowrap;">
      <INPUT type="checkbox" name="user_registered" class="checkbox2"  value="22"   >
   </div>
</td>
<td>
   <td> </td>

Upvotes: 0

Views: 2651

Answers (2)

tvanfosson
tvanfosson

Reputation: 532465

For each div, sum the values of the (checked?) checkboxes, then find the next TD (next sibling of parent TD) and use the total as the contents of the TD you've found.

$('div.checkboxes').each( function() {
   var total = 0;
   $(this).find('input:checkbox:checked').each( function() {
       total += parseInt( $(this).val() );
   });
   $(this).closest('td').next('td').html(total);
});

Upvotes: 2

Nick Craver
Nick Craver

Reputation: 630429

You can do it like this:

​$("div.checkboxes").each(function() {
    var total = 0;
    $(this).find(":checkbox").each(​​​​​​​​​​​​​​​​function() {
        total += parseInt(this.value, 10);
    });
    $(this).parent().next().text(total);
});

You can give it a try here, you'll want to change .find(":checkbox") to .find(":checkbox:checked") if you only want to sum the checked values.

Upvotes: 2

Related Questions