scorpio1441
scorpio1441

Reputation: 3088

jquery calculate html values next to checked checkboxes

My head is not thinking right today. Could any of you help? =) Only checked int values in second column need to be calculated and alerted in sum.

<table width="100%">
  <tr><td>Product Name</td><td>Price $</td></tr>
  <tr><td><input type="checkbox"> Product 1</td><td>200</td></tr>
  <tr><td><input type="checkbox"> Product 2</td><td>300</td></tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
  $('input').change(function() {
    var sum = 0;
    $("input:checked").each(function(){
      sum += parseInt($("input:checked").closest('td').next().html());
    });
    alert(sum);
  });
</script>

Thanks.

Upvotes: 2

Views: 1141

Answers (2)

Andrew Whitaker
Andrew Whitaker

Reputation: 126042

Try this:

$('input:checkbox').change(function() {
    var sum = 0;
    $("input:checked").each(function() {
        sum += parseInt($(this).closest('td').next().text(), 10);
    });
    alert(sum);
});

You need to listen for the change event on all checkboxes, not only those :checked. Also, be sure to pass the radix parameter to parseInt. Finally, this will refer to the item being evaluated in the each function.

Example: http://jsfiddle.net/38AeT/

Upvotes: 3

Michael Berkowski
Michael Berkowski

Reputation: 270599

Looks like you should be using $(this) inside the .each() to find the closest <td> to the currently selected checkbox in the loop.

  // Bind to all checkboxes...
  $('input[type="checkbox"]').change(function() {
    var sum = 0;
    $("input:checked").each(function(){
      // Use $(this) here
      sum += parseInt($(this).closest('td').next().html(), 10);
      // Always use the optional radix to parseInt() -----^^^^^
    });
    alert(sum);
  });

Upvotes: 4

Related Questions