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

186
May 01, 2017, at 06:32 AM

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!

Answer 1

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);
Answer 2

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

READ ALSO
JQuery Datatables: order by data

JQuery Datatables: order by data

How can I order column by a value passed to data instead of custom rendered content?

485
Jquery calculate the total of all textboxes (addition and subtraction)

Jquery calculate the total of all textboxes (addition and subtraction)

Hello I am trying to calculate the total of multiple fields in a row (my code will contain multiple rows) on key press (some of them uses addition method and some of them uses subtract method) but as I am newbie I am not too much familiar to JQueryIn...

267
clearInterval on click

clearInterval on click

I have a simple script where random keywords appear at a timed intervalWhat I'd like is for them to stop appearing after one is clicked on

273
Closures in Typescript

Closures in Typescript

I have Angular2/Typescript websiteI am using PrimeNG frameowrk for CSS

322