开发者

jQuery adding multiple text boxes

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.

开发者_StackOverflow社区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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜