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 ;
}
NaN (Not a Number) is a numeric data type that means an undefined value or value that cannot be represented, especially results of floating-point calculations.
Javascript null represents the intentional absence of any object value. The undefined property indicates that the variable has not been assigned a value or not declared at all. The NaN property represents a “Not-a-Number” value. The NaN property indicates that a value is not a legitimate number.
NaN values are generated when arithmetic operations result in undefined or unrepresentable values. Such values do not necessarily represent overflow conditions. A NaN also results from attempted coercion to numeric values of non-numeric values for which no primitive numeric value is available.
NaN is an error value that means not a number. However, JavaScript considers the type of NaN to be number. Infinity is a value so big it can't be represented by JavaScript numbers. It acts mostly like mathematical infinity.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With