Search code examples
javascriptundefinednannumerical

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

Solution

  • 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.