我正在尝试使用 .each()
从输入字段中获取值,并将它们相加以在另一个输入值中显示总和。但不幸的是,尽管使用了 parseInt() 我还是无法得到总和。
HTML
<input type=text name=value[] id=value class="value">
<input type=text name=value[] id=value class="value">
<input type=text name=totalvalue id=totalvalue>
JavaScript
var totalvalue = parseInt(0);
$(document).on("focusout",".value",function() {
$(".value").each(function() {
totalvalue = parseInt(totalvalue + $(this).val());
});
$("#totalvalue").val(totalvalue);
});
最佳答案
你正在解析的行是在说
Add the
totalValue
to the string from the input, then parse the result.
这就是它串联的原因。相反,您需要添加 parseInt()
的 totalValue
outside 以便它说
Take the take the
totalValue
and add the parsed input value to it.
像这样
totalvalue = totalvalue + parseInt($(this).val());
这可以进一步缩短为
totalvalue += parseInt($(this).val());
关于Javascript - 从输入返回连接而不是变量总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44940503/