Search code examples
javascripthtmlnumbersaverage

Javascript: Average of 2 user input values


I apologize for the basic question but I have been trying to make this work for a long time and I just can't seem to get this code to return a value.

I am embarrassed to admit how long I have been attempting to make it work, and how many StackOverflow questions that were related that I have looked at, however, none were as simple as my code, and when I attempted to make something closer to how mine looked, it just wouldn't alert anything.

The idea is the following:

  • User inputs 2 numbers,
  • clicks the button,
  • and is alerted the average of the numbers they input.

My alert has been NaN no matter how many iterations I have made. I could really use some advice. Thanks in advance!

<html>
	<head>
		<title> Javascript </title>
	<body>
		<p> Enter two number for an average below </p>
		<p> Number 1<input type="text" id="userInput1"></input></p>
    	<p> Number 2<input type="text" id="userInput2"></input></p>
    	<button id="averageButton"> Calculate</button>
   
    <script type="text/javascript">
    	function average(a, b) {
    		return ((a + b) /2);
    	}

    	document.getElementById("averageButton").onclick = function (){
   	 		var a = document.getElementById("userInput1").value;
			var b = document.getElementById("userInput2").value;    		
    		alert(average());
		}
	</script>
    </body>

</html>


Solution

  • You failed to pass the numbers a,b to your function - a simple mistake.

    But since the inputs are seen as strings you also need to convert them to numbers a*1

    See commented code

    <html>
    	<head>
    		<title> Javascript </title>
    	<body>
    		<p> Enter two number for an average below </p>
    		<p> Number 1<input type="text" id="userInput1"></input></p>
        	<p> Number 2<input type="text" id="userInput2"></input></p>
        	<button id="averageButton"> Calculate</button>
       
        <script type="text/javascript">
        	function average(a, b) {
        		// force the input as numbers *1
            return ((a*1 + b*1) /2);
        	}
    
        	document.getElementById("averageButton").onclick = function (){
       	 		var a = document.getElementById("userInput1").value;
    			var b = document.getElementById("userInput2").value;    		
        		// pass the numbers to the average function!
            alert(average(a,b));
    		}
    	</script>
        </body>
    
    </html>