开发者

Javascript Simple Calculation giving NAN or 0

开发者 https://www.devze.com 2023-01-29 08:24 出处:网络
Can anyone work out why this does not开发者_开发百科 work. Produces NAN and if reset for a Number(document on var inputs produces 0. The script is supposed to add up an indefinite number of fields sta

Can anyone work out why this does not开发者_开发百科 work. Produces NAN and if reset for a Number(document on var inputs produces 0. The script is supposed to add up an indefinite number of fields starting with an ID of product_total_price_PRI_ ... .

Obviously I've missed something and have got a headache from trying to see it.

function getFields() {
    var inputs = document.getElementsByTagName('input');
    var result = 0;
    for( var i = 0; i < inputs.length; i++ ) {
        if( inputs[i].id.indexOf('product_total_price_PRI_') == 0 );
           result += parseFloat(inputs[i].value); 
     }

    alert(result);
}


Your if() syntax is off, there's a ; ending the statement so your result += is always running, it should be:

function getFields() {
    var inputs = document.getElementsByTagName('input');
    var result = 0;
    for( var i = 0; i < inputs.length; i++ ) {
        if( inputs[i].id.indexOf('product_total_price_PRI_') == 0 ) //no ; here
           result += parseFloat(inputs[i].value); 
     }

    alert(result);
}


You have a ; after your if that needs to be removed:

if( inputs[i].id.indexOf('product_total_price_PRI_') == 0 )
    result += parseFloat(inputs[i].value); 

Also it's always a good idea to check if the string entered inside the input is a number:

if( inputs[i].id.indexOf('product_total_price_PRI_') == 0 )
{
    var temp = parseFloat(inputs[i].value);
    if (!isNaN(temp)) {
        result += temp; 
    }
}


Blank fields evaluate to NaN, not 0. You need to ensure you don't add an NaN values

function getFields() {
    var inputs = document.getElementsByTagName('input');
    var result = 0;
    for (var i = 0; i < inputs.length; i++ ) {
        if (inputs[i].id.indexOf('product_total_price_PRI_') == 0) {
            var val = parseFloat(inputs[i].value);
            if (val - 0 == val) // will be false if val is NaN
                result += val; 
        }
    }

    alert(result);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消