对于同一个类,我有多个输入数字字段,我必须对它们求和,但是当我尝试使用我的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和jquery,但我必须获得每个字段的id才能做到这一点,我想为具有相同类的每个人这样做,因为它们是动态字段。
另外,我的另一部分工作是获取这些字段的每个名称并存储它们,这样我就可以在js中有一个数组,其中包含输入的名称和数值,但我不知道如何做,因为它们是动态的
发布于 2019-05-17 04:55:20
您可能正在解析不是整数的内容。然后,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;
});
发布于 2019-05-17 05:10:25
如果其中一个输入值为空,则parseInt返回NAN。所以你最好使用IsNan函数进行检查。如果输入为空,则赋值0。例如:
var x= parseInt($('#abc').val());如果(isNaN(x)) x= 0;
https://stackoverflow.com/questions/56176230
复制相似问题