subtrude
subtrude

Reputation: 35

How to get JS function return from HTML button into heading?

I'm making a multiplication practice website for my science fair, and I need some help. I want the website to show whether the user input was correct or incorrect compared to the right answer. I think I coded the function right, and I know to call it with a submit button. However, I have some trouble accessing the return from the function. Where does the function return go and how do I access it?

    		//get random integer
    		var num1 = Math.floor(Math.random() * (14 - 7 + 1) ) + 7;
    		var num2 = Math.floor(Math.random() * (14 - 7 + 1) ) + 7;
    		var userAnswer = 0
    		document.getElementById('num1').innerHTML = num1;
    		document.getElementById('num2').innerHTML = num2;
    		
    		
    		
    		function validateAnswer(num1, num2) {
    			var realAnswer = num1*num2;
    			var userAnswer = document.getElementById('userAnswer').value;
    			if (realAnswer == userAnswer){
    				return 'correct';
    			}
    			else {
    				return 'incorrect';			
    			}
    
    		}
    	<h1>Multiplication Practice</h1>
    	<div class="equation">
    		<h2 id="num1" class="num1multiply"></h2>
    		<span class="multiplicationSign">&#215;</span>
    		<h2 id="num2" class="num2multiply"></h2>	
    	</div class="equation">
    	<br>
    	<input type="integer" id="userAnswer">
    	<button onclick="validateAnswer(num1, num2);" id="submit">Submit</button>
    	<br>
    	<h2 id="validateAnswer"></h2>
    	<br>
    	<br>
    	<a class="back" href="main.html">back</a>

Upvotes: 2

Views: 139

Answers (1)

jwatts1980
jwatts1980

Reputation: 7356

Since you are calling the validateAnswer() function from the onclick, I would recommend NOT returning anything. JavaScript functions do not have to have a return value. It can just perform an action. In this case, I would recommend updating the function to have it set the result into the document.

function validateAnswer(num1, num2) {
    var realAnswer = num1*num2;
    var userAnswer = document.getElementById('userAnswer').value;
    var result;
    if (realAnswer == userAnswer){
        result = 'correct';
    }
    else {
        result = 'incorrect';         
    }
    document.getElementById('validateAnswer').innerHTML = result;
}

Upvotes: 2

Related Questions