Garrett Harinen
Garrett Harinen

Reputation: 3

having trouble with doing math with text box value and a calculated value

I am using a function in my code that takes and does math with a value from a text box that the user writes in and also a calculated value that is used earlier in the page. If the text box value is not a positive number an alert will appear showing that the value must be a positive number. If it is a positive number, it shows an alert with the outcome of the math. The only problem is, when this happens, what appears is where the number should be there is instead "NaN". I believe this is because the values I'm using aren't actually numbers but I'm not sure how to fix this.

function computeTotalDistance(result) {
        var total = 0;
        var myroute = result.routes[0];
        for (var i = 0; i < myroute.legs.length; i++) {
          total += myroute.legs[i].distance.value;
        }
        total = (total / 1000) * 0.621371;
        document.getElementById('total').innerHTML = total;
      }

function calc_gallons() {
        var total = parseInt(document.getElementById("total").value)
		var averagempg = parseInt(document.getElementById("averagempg").value);
		var gallons = 0;
		if (averagempg > 0) {
			gallons = total / averagempg
			window.alert("This trip requires " + gallons + " gallon(s). Have safe travels!");
		}else {
			window.alert("Your average MPG must be a positive number in order to calculate the gallons required for this trip.");
		}
      }

#this is the text box and the button that does the function
<p>Your Average MPG:<input type="text" id="averagempg" name="MPG"></p>
<button type="button" name="Calculate" onclick="calc_gallons()">Calculate!

Upvotes: 0

Views: 84

Answers (2)

rie
rie

Reputation: 296

Better use explicit type conversion:

var total = Number(document.getElementById("total").value);
var averagempg = Number(document.getElementById("averagempg").value);

parseInt then called on empty string ('') returns NaN.

If the first character cannot be converted to a number, parseInt returns NaN.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

Examples: https://coderwall.com/p/kwhkig/javascript-number-conversion

Upvotes: 1

yezzz
yezzz

Reputation: 3020

The problem is getting total inside calc_gallons(). You're trying to get it from value, but you have it in a span. So either put total in a disabled input, or get it via innerHTML:

var total = parseInt(document.getElementById("total").innerHTML);

Are you sure you used the console? I failed to see the issue at first, and the following revealed that total is NaN:

 console.log("total:", total, typeof total);
 console.log("averagempg:", averagempg, typeof averagempg);

Upvotes: 0

Related Questions