为了账号安全,请及时绑定邮箱和手机立即绑定

倍数输入数字字段jquery的总和值

倍数输入数字字段jquery的总和值

墨色风雨 2021-06-02 13:39:19
我有多个具有相同类的输入数字字段,我必须对它们求和,但是当我尝试使用我的 javascript 时,我总是得到 NaN 结果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);});input的html是这个,php生成的,一个表的每一行一个<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">我不知道它行不通,它只适用于没有 jquery 的 js,但我必须获得每个字段的 id 才能做到这一点,我想为所有具有相同类的人做到这一点,因为它们是动态字段PS 我工作的另一部分是获取这些字段的每个名称并存储它们,这样我就可以在 js 中有一个数组,其中我有输入的名称和他的数值,但我不知道该怎么做,因为它们是动态的
查看完整描述

3 回答

?
开满天机

TA贡献1786条经验 获得超12个赞

您可能正在解析不是整数的内容。然后 parseInt 将不起作用并返回 NaN。如果对 NaN 求和,则它仍然是 NaN,例如:


// 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 来“否定”它:


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

要将这个概念集成到你的代码中,你会得到类似的东西:


let total = 0;

$('.input-n-pro').each(() => {

  let valueInString = $(this).val();

  let actualValue = parseInt(valueInString) || 0;

  total += actualValue;

});


查看完整回答
反对 回复 2021-06-03
?
慕工程0101907

TA贡献1887条经验 获得超5个赞

如果输入值之一为空,则 parseInt 返回 NAN。因此,您可以更好地使用 IsNan 函数进行检查。如果输入为空,则赋值为 0。例如;

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


查看完整回答
反对 回复 2021-06-03
  • 3 回答
  • 0 关注
  • 117 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信