使用javascript自动计算输入值的总和 [英] auto calculate the sum of input values with javascript
本文介绍了使用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;
这篇关于使用javascript自动计算输入值的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文