views:

84

answers:

2

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>
+2  A: 

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);
});
tvanfosson
+2  A: 

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.

Nick Craver
absolute gold! thank you!
roger rover