1

我制作了一个动态表单,如果我删除一行,那么循环结果是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);
    }
});
4

3 回答 3

8

检查值是否是这样的数字:

var quantity=parseFloat($('#quantity' + i).val());    
if(isNaN(quantity)){
    quantity=0;
}
于 2013-10-10T13:48:36.843 回答
0

您可以使用 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);
}
于 2013-10-10T13:49:39.670 回答
0

You can check to see if it's NaN

var quantity = !isNaN($('#quantity' + i).val()) ? parseFloat($('#quantity' + i).val(), 2) : 0;
于 2013-10-10T13:50:03.683 回答