首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >多个输入数字字段jquery的求和值

多个输入数字字段jquery的求和值
EN

Stack Overflow用户
提问于 2019-05-17 04:35:00
回答 2查看 498关注 0票数 0

对于同一个类,我有多个输入数字字段,我必须对它们求和,但是当我尝试使用我的javascript时,我总是得到NaN结果

代码语言:javascript
复制
var arrNumber = new Array(); //contain the number of specific input field

        var totale;
        $(".input-n-pro").bind('keyup mouseup', function () {
             totale = 0;
        $('.input-n-pro').each(function(){
        var this_num = $(this).val();
            totale = parseInt(this_num)+parseInt(totale);
        })
        console.log("totale="+totale);
});

输入的html是这样的,由php生成,对应于表的每一行。

代码语言:javascript
复制
<input type="number" name="<?php echo $data["name"];?>" min="0" max="500" placeholder="0" class="form-control input-xs input-n-pro" style="display: inline">

我不知道它会不会起作用,它只适用于js和jquery,但我必须获得每个字段的id才能做到这一点,我想为具有相同类的每个人这样做,因为它们是动态字段。

另外,我的另一部分工作是获取这些字段的每个名称并存储它们,这样我就可以在js中有一个数组,其中包含输入的名称和数值,但我不知道如何做,因为它们是动态的

EN

回答 2

Stack Overflow用户

发布于 2019-05-17 04:55:20

您可能正在解析不是整数的内容。然后,parseInt将无法工作,并返回NaN。如果你对一个NaN求和,那么它仍然是一个NaN,例如:

代码语言:javascript
复制
// working testcase:
const testArray = ['2', '3', '4'];
let total = 0;
for (value of testArray) {
    total += parseInt(value);
}
// returns 9
console.log(total);

// your testcase:
const testArray2 = ['2', '3', 'notANumber'];
let total2 = 0;
for (value of testArray2) {
    total2 += parseInt(value);
}
// returns NaN since we are adding 2 + 3 + NaN = NaN
console.log(total2);

因此,解决方案是通过将NaN视为0来“否定”它:

代码语言:javascript
复制
    //  solution:
    const myArray = ['2', '3', 'notANumber', '4'];

    let total = 0;
    for (value of myArray) {
        // treat NaN, undefined or any falsey values as 0.
        total += parseInt(value) || 0;
    }

    //  returns 9
    console.log(total);

要将此概念集成到您的代码中,您将获得如下内容:

代码语言:javascript
复制
let total = 0;
$('.input-n-pro').each(() => {
  let valueInString = $(this).val();
  let actualValue = parseInt(valueInString) || 0;
  total += actualValue;
});

票数 3
EN

Stack Overflow用户

发布于 2019-05-17 05:10:25

如果其中一个输入值为空,则parseInt返回NAN。所以你最好使用IsNan函数进行检查。如果输入为空,则赋值0。例如:

var x= parseInt($('#abc').val());如果(isNaN(x)) x= 0;

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56176230

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档