'HTML / Javascript ReferenceError: Can't find variable
I've made extensive use of the search function and whilst there seem to be many instances of this problem, none are close enough for me to glean a solution to my variant of the problem.
I'm using vanilla Javascript to create a multiplication game. When the button is pressed either by the user pressing 'Enter' or clicking the button the console shows me this error:
ReferenceError: Can't find variable: checkAnswer
Here is the code:
var user_answer;
for(var x in questions){
document.getElementById("bronze").innerHTML = '<p>' + questions[x] + '</p>';
document.getElementById("bronze").innerHTML += '<p><input type="number" id="user_input"></p>';
document.getElementById("bronze").innerHTML += '<p><button type="button" id="submit_button" onclick="checkAnswer()">Enter</button></p>';
var user_input = document.getElementById("user_input");
user_input.addEventListener("keyup", function(event){
if(event.keyCode == 13){
event.preventDefault();
document.getElementById("submit_button").click();
}
});
function checkAnswer(){
user_answer = document.getElementById("user_input").value;
if(user_answer == answers[x]){
alert('Correct!');
} else {
alert('Wrong!');
}
}
}
Edit to say that questions and answers are arrays each containing the questions and corresponding answers in the same position. So questions will be like [1x2,2x2,...] and answers [2,4,...]
Solution 1:[1]
Thank you all for such fast replies. You were all correct so I couldn't pick one answer but here's what I did:
- Moved the checkAnswer function outside the for loop.
- Made 'answers' and 'x' global variables by declaring them outside the function(s).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Reporter |
