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

多个输入数字段jquery的和值

多个输入数字段jquery的和值

侃侃尔雅 2019-04-17 14:15:59
我有多个具有相同类的输入数字字段,我必须总结它们但是当我尝试使用我的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);});输入的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">我不知道它不起作用,它只使用js withous jquery,但我必须得到每个字段的id来做到这一点,我想为同一个班级的每个人做这个,因为他们是dinamic字段PS我工作的另一部分是获取这些字段的每个名称并存储它们以便我可以在js中有一个数组,其中我有输入名称和数字值,但我不知道该怎么做因为它们是dinamic
查看完整描述

4 回答

?
牧羊人nacy

TA贡献1862条经验 获得超7个赞

您可能正在解析不是整数的东西。然后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来“否定”NaN:


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

});


查看完整回答
反对 回复 2019-05-17
?
慕盖茨4494581

TA贡献1850条经验 获得超11个赞

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

var x = parseInt($('#abc')。val()); if(isNaN(x))x = 0;


查看完整回答
反对 回复 2019-05-17
  • 4 回答
  • 0 关注
  • 349 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号