2

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.

2 Answers 2

4

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);
  });
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot! I should drink less wine while programming.
Yeah, I guess it's better none or more.
3

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.