2

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>

1 Answer 1

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.