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

我有多个具有相同类的输入数字字段,我必须对它们求和,但是当我尝试使用我的 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 中有一个数组,其中我有输入的名称和他的数值,但我不知道该怎么做,因为它们是动态的


墨色风雨
浏览 118回答 3
3回答

开满天机

您可能正在解析不是整数的内容。然后 parseInt 将不起作用并返回 NaN。如果对 NaN 求和,则它仍然是 NaN,例如:// working testcase:const testArray = ['2', '3', '4'];let total = 0;for (value of testArray) {&nbsp; &nbsp; total += parseInt(value);}// returns 9console.log(total);// your testcase:const testArray2 = ['2', '3', 'notANumber'];let total2 = 0;for (value of testArray2) {&nbsp; &nbsp; total2 += parseInt(value);}// returns NaN since we are adding 2 + 3 + NaN = NaNconsole.log(total2);因此,解决方案是通过将 NaN 视为 0 来“否定”它:&nbsp; &nbsp; //&nbsp; solution:&nbsp; &nbsp; const myArray = ['2', '3', 'notANumber', '4'];&nbsp; &nbsp; let total = 0;&nbsp; &nbsp; for (value of myArray) {&nbsp; &nbsp; &nbsp; &nbsp; // treat NaN, undefined or any falsey values as 0.&nbsp; &nbsp; &nbsp; &nbsp; total += parseInt(value) || 0;&nbsp; &nbsp; }&nbsp; &nbsp; //&nbsp; returns 9&nbsp; &nbsp; console.log(total);要将这个概念集成到你的代码中,你会得到类似的东西:let total = 0;$('.input-n-pro').each(() => {&nbsp; let valueInString = $(this).val();&nbsp; let actualValue = parseInt(valueInString) || 0;&nbsp; total += actualValue;});

慕工程0101907

如果输入值之一为空,则 parseInt 返回 NAN。因此,您可以更好地使用 IsNan 函数进行检查。如果输入为空,则赋值为 0。例如;var x= parseInt($('#abc').val());&nbsp;如果 (isNaN(x)) x = 0;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript