2

I wonder if anyone could help me.

I have a web page where there are some text boxes (dynamic amount, could be 3, could be 30) and each one a user can enter a number and I have a total count at the bottom.

At present I have this:

$('input.qty').change(function() {
// Get the current total value
var total = $('#total');
// Update it with the changed input's value
total.val(parseInt(total.val()) + parseInt($(this).val()));
});

Example HTML:

<td><input type="text" class="qty" value="0" /></td>
<td><input type="text" class="qty" value="0" /></td>
<td><input type="text" class="qty" value="0" /></td>
<td><input type="text" id="total" value="0" /></td>

which adds fine first time, but when you start changing values it simply adds the new amount to the total rather then adding all the boxes up.

How can I sort this? Perhaps use the each attr somehow?

1 Answer 1

2

You can loop through them all using a .each() and sum them up, like this:

$('input.qty').change(function() {
  var sum = 0;
  $('input.qty').each(function() { sum += parseInt(this.value, 10); });
  $('#total').val(sum);
});

You can give it a try here, if you want it to calc on every keypress then use .keyup() instead of .change(), like this.

Sign up to request clarification or add additional context in comments.

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.