Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

276
Views
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,...]

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Thank you all for such fast replies. You were all correct so I couldn't pick one answer but here's what I did:

  1. Moved the checkAnswer function outside the for loop.
  2. Made 'answers' and 'x' global variables by declaring them outside the function(s).
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!