[英]Javascript Calculate the sum off multiple HTML-input values
im looking for some Javascript code to calculate the sum off multiple HTML-input values. 我正在寻找一些Javascript代码来计算多个HTML输入值的总和。 The amount off inputs are dynamic so i'm looking for something like "for each" input.
关闭输入的数量是动态的,所以我正在寻找类似“为每个”输入的东西。
the format off the numbers is 1 000,00 (space as thousand separator and , as decimal separator). 数字格式为1 000,00(空格为千位分隔符,小数分隔符)。
My inputs are in and array so the ID's and NAME's is like this: 我的输入是和数组,所以ID和NAME是这样的:
input_sum1[0]
input_sum1[1]
input_sum1[2]
input_sum2[0]
input_sum2[1]
input_sum2[2]
Any suggestions? 有什么建议么?
Thanks in advance! 提前致谢!
A jQuery example. 一个jQuery示例。 Provided a class name for your text boxes.
为文本框提供了类名。
<script>
$(document).ready ( function () {
$("#btn1").click ( function () {
var resultVal = 0.0;
$(".test").each ( function() {
resultVal += parseFloat ( $(this).val().replace(/\s/g,'').replace(',','.'));
});
alert ( resultVal );
});
});
</script>
<input type="text" value="10" class="test" />
<input type="text" value="20" class="test" />
<input type="text" value="30.50" class="test" />
<input type="text" value="1" class="test" />
<input type="text" value="1" class="test" />
<br />
<button id="btn1">click</button>
id
, it makes life easier. id
,它让生活更轻松。 document.getElementById
(or if you're using Prototype or jQuery, they have shorthand ways to do that). document.getElementById
获取对表单对象的引用(或者如果您使用的是Prototype或jQuery,它们可以使用简写的方法)。 elements
array. elements
数组。 value
property; value
属性; it'll be a string. parseFloat
to get the value. parseFloat
获取值。 You don't get locale-aware number parsing in JavaScript, so you'll have to do a string replacement to get something parseFloat()
will handle: 您没有在JavaScript中获得可识别区域设置的数字解析,因此您必须执行字符串替换以获取
parseFloat()
将处理的内容:
<div id="inputs">
<input type="text" />
<input type="text" />
...
</div>
<p>
<input type="button" id="summer" value="Sum" />
<input type="text" id="sum" />
</p>
<script type="text/javascript">
document.getElementById('summer').onclick= function() {
var sum= 0;
var inputs= document.getElementById('inputs').getElementsByTagName('input');
for (var i= inputs.length; i-->0;) {
var v= inputs[i].value.split(',').join('.').split(' ').join('');
if (isNaN(+v))
alert(inputs[i].value+' is not a readable number');
else
sum+= +v;
}
document.getElementById('sum').value= sum;
};
</script>
(You don't need a <form> element or any input names if it's a purely client-side thing you don't ever expect to submit.) (如果您不希望提交纯粹的客户端内容,则不需要<form>元素或任何输入名称。)
Note this uses floating point numbers, so the sum of 0.1 and 0.2 may not be exactly what you think. 请注意,这使用浮点数,因此0.1和0.2之和可能与您的想法不完全相同。 If you are looking at money amounts, floating point isn't suitable and you'll have to come up with a fixed-point or decimal-based number parser.
如果您正在查看金额,浮点数不合适,您将不得不想出一个定点或基于十进制的数字解析器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.