views:

71

answers:

1

Hi all,

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? Any suggestions would be much appreciated...

Adi.

+2  A: 

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.

Nick Craver