使用javascript自动计算输入值的总和

问题描述:

我有一个html页面,其中包含许多动态创建的输入框。文本框的数量每次都不同。
我想计算用户输入的数字之和,并显示它。当用户删除一个数字时,总和应自动计算。

I've an html page which has many dynamically created input boxes. The number of text boxes vary each time. I want to calculate the sum of the numbers the user has entered, and disply it. When the user delete one number the sum should auto calculate.

我如何使用javascript进行操作?
谢谢

How can i do it with javascript? Thanks

在jQuery中,这样的事情应该有一些假设:

In jQuery something like this should work with a few assumptions:

$('.toAdd').live('change', function() {
  var total = 0;

  $('.toAdd').each(function () {
    total += $(this).val();
  });

  $('#total').val(total);
});

假设您的输入字段都具有toAdd类并且您的最终输入字段具有ID为'total'。

The assumptions being that your input fields all have the class 'toAdd' and that your final input field has an ID of 'total'.

在纯JS中:

var elems = document.getElementsByClassName('toAdd');

var myLength = elems.length,
total = 0;

for (var i = 0; i < myLength; ++i) {
  total += elems[i].value;
}

document.getElementById('total').value = total;