Javascript-返回级联而不是输入中变量的总和 [英] Javascript - returning concatenates instead of sum of variables from input

查看:49
本文介绍了Javascript-返回级联而不是输入中变量的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用.each()从输入字段中获取值,并将它们相加以在另一个输入值中显示总和.但是不幸的是,尽管使用parseInt(),我还是无法获得总和.

I am trying to get values from input field using .each() and adding them to show the sum in another input value. But unfortunately in spite of using parseInt() I am unable to get sum.

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);
});

JSFiddle演示

推荐答案

解析行在说的是

totalValue添加到输入的字符串中,然后解析结果.

Add the totalValue to the string from the input, then parse the result.

这就是级联的原因.相反,您需要添加parseInt()totalValue 外部,这样它就是说

Which is why it's concatenating. Instead, you need to add the totalValue outside of the parseInt() so that it's saying

以Take totalValue并将解析后的输入值添加到其中.

Take the take the totalValue and add the parsed input value to it.

totalvalue = totalvalue + parseInt($(this).val());

这可以进一步缩短为

totalvalue += parseInt($(this).val());

这篇关于Javascript-返回级联而不是输入中变量的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆