Undefined / NaN error in output

This is my first post on stackoverflow, I encountered an error in the following code, when viewing the JS element / console in firefox, an error does not appear, but for some reason the output after the calculation shows an undefined / NaN error. User input 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 ; } 
+5
source share
4 answers
 var weight = parseFloat(document.getElementById("weight")).value; 

This is not like parseFloat. You are trying to call the value property on a double. Extend your bracket.

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

I suggest using console.log(weight); or other values ​​around your code so you can more easily point out these issues.

+7
source
 parseFloat(document.getElementById("weight")).value 

it should be

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

With practice, you will develop an eye for such things. Until then, sprinkle your code with alert () operations to sort things out. Remember to take them when done. Remember that doing math on NaN is not an error, so there is no error message.

+4
source

You have closed the brackets in the first line of your code too soon. It should probably be like this:

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

Javascript cannot parse the DOM element for float .;)

+3
source

If the weight value does not match any of the specified conditions, then the cost variable will not be initialized, and any calculations using undefined will result in undefined .

+1
source

Source: https://habr.com/ru/post/1233888/


All Articles