Walrus
Walrus

Reputation: 20444

Javascript Simple Calculation giving NAN or 0

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);
}

Upvotes: 1

Views: 1673

Answers (3)

Brad Mace
Brad Mace

Reputation: 27886

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);
}

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038730

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; 
    }
}

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630379

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);
}

Upvotes: 3

Related Questions