javascript 如何从字段值中删除 NaN 并显示值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19297009/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to remove NaN from field value and show value?
提问by Arsal Ali
I make a dynamic form, if i delete a row then in loop result is NaN
of the deleted element i want when i delete element its 0 value pass not NaN
. Like i delete 5th element when 1=5 it shows NaN
. How to remove this error and instead 0 will be add in sum value, how i do?
我制作了一个动态表单,如果我删除一行,那么NaN
当我删除元素时,循环结果是我想要的已删除元素,它的 0 值不传递NaN
。就像我在 1=5 时删除第 5 个元素一样NaN
。如何消除此错误,而是将 0 添加到总和值中,我该怎么办?
$("body").on('change', '.quantity', function() {
var that = $(this);
if ($('#itemcounter').val()==""){
$('#itemscounter').val("1");
var counter=$('#itemscounter').val();
var quantity=$('#quantity').val();
var unitprice=$('#unitprice').val();
var linetotal=quantity*unitprice;
that.parent().find('.linetotal').val(linetotal)
$("#invoicetotalamount").val(+linetotal)
var discount=document.getElementById('discount').value ;
var discountamount= discount/100 * linetotal;
var amount=linetotal-discountamount;
$("#balanceamount").val(+amount);
} else {
var counter=$('#itemscounter').val();
var quantity=$('#quantity').val();
var unitprice=$('#unitprice').val();
var linetotal=quantity*unitprice;
$('#linetotal').val(+linetotal);
var sum=linetotal;
for (i = 2; i <=counter; i++) {
var quantity=parseFloat($('#quantity' + i).val());
var unitprice=parseFloat($('#unitprice' + i).val());
var linetotal=quantity*unitprice;
$('#linetotal' + i).val(+linetotal);
alert(sum);
sum=+sum +(+(linetotal));
}
$("#invoicetotalamount").val(+sum);
var discount=document.getElementById('discount').value ;
var discountamount= discount/100 * sum;
var amount=sum-discountamount;
$("#balanceamount").val(+amount);
}
});
回答by TheMobileMushroom
Check the value if its a number like this:
检查值是否是这样的数字:
var quantity=parseFloat($('#quantity' + i).val());
if(isNaN(quantity)){
quantity=0;
}
回答by Anup
you can check it with if else loop for dynamic data:
您可以使用 if else 循环检查动态数据:
var str_val = $('#itemscounter').val();
if(str_val == NaN){
str_val =0; //use str_val at the place you want
alert(str_val);
}
回答by Matthew Riches
You can check to see if it's NaN
你可以检查它是否是 NaN
var quantity = !isNaN($('#quantity' + i).val()) ? parseFloat($('#quantity' + i).val(), 2) : 0;