Prabh Rai
Prabh Rai

Reputation: 53

undefined / NaN error in output

This is my first post on stackoverflow, i am encountering error in the following code , no error shows in inspect element / JS console in firefox but for some reason the ouput after calculation is displaying undefined / NaN error . The input from user is parsed in Float.

code:

function costtoShip(){

    // get input 

    var weight = parseFloat(document.getElementById("weight")).value ;
    var msg;
    var cost;
    var subtotal;

    // calculation

    if ( weight >= 0.00 && weight <= 150.00 ) {
        cost = 20.00;
    }

    else if ( weight >= 151.00 && weight <= 300.00 ) {
        cost = 15.00;
    }

    else if ( weight >= 301.00 && weight <= 400.00 ) {
        cost = 10.00;
    }    


   subtotal = weight * cost ;
   msg = "<div> Total Weight is " + weight + "</div>" ;
   msg = msg + "<div> Subtotal is " + subtotal + "</div>" ;


   // send output

    document.getElementById("results").innerHTML = msg ;
}

Upvotes: 5

Views: 1399

Answers (4)

JsingH
JsingH

Reputation: 189

If weight value doesn't meet any of the specified conditions then cost variable will not be initialized and any calculation using undefined will result in undefined.

Upvotes: 1

sfandler
sfandler

Reputation: 640

You closed the brackets on the first line of your code too early. It's probably supposed to be like this:

var weight = parseFloat(document.getElementById("weight").value);

Javascript is not able to parse a DOM element to float. ;)

Upvotes: 3

dspeyer
dspeyer

Reputation: 3026

parseFloat(document.getElementById("weight")).value

should be

parseFloat(document.getElementById("weight").value)

With practice, you'll develop an eye for things like this. Until then, sprinkle your code with alert() statements to dig into this sort of thing. Just remember to take them out when you're done. Remember that doing math on NaN isn't an error, hence no error message.

Upvotes: 4

Sterling Archer
Sterling Archer

Reputation: 22395

var weight = parseFloat(document.getElementById("weight")).value;

This is not how to parseFloat. You're trying to call a value property on a double. Move your parenthesis out.

var weight = parseFloat(document.getElementById("weight").value);

I suggest using console.log(weight); or other values around your code so you can easier pin point these issues.

Upvotes: 7

Related Questions