0

I am attempting to get the user input from an tag and use same in a JS function.

The HTML / JS:

<form>
        <label for="guess">Enter a number between 1 and 10</label><br>
        <input type="text" id="guess" value="">
        <input type="button" value="Submit" onclick="guess()">

    </form>
    <p id="answer">ANSWER</p>



function guess(){
        var userGuess = document.getElementById("guess").value;
        var random = Math.ceil(Math.random()*10);
        if (userGuess == random){
            document.getElementById("answer").innerHTML="Correct!";
        }else{
            document.getElementById("answer").innerHTML="Incorrect, answer was " + random;
        }
    }

I keep getting a runtime error :

Uncaught TypeError: guess is not a function
    at HTMLInputElement.onclick (Week 6 JavaScript Homework.html?guess=:13)
onclick @ Week 6 JavaScript Homework.html?guess=:13

This error is thrown on line:

<input type="button" value="Submit" onclick="guess()">

I have check the syntax and I cant see what the problem is. Input appreciated.

dancingbush
  • 2,131
  • 5
  • 30
  • 66

1 Answers1

2

It's part of the HTML5 spec to store elements with id myElementId as window.myElementId (which is also myElementId in the global scope). Basically, guess was a reference to the element input#guess, instead of the function guess().

Renaming either fixes the problem.

function guess() {
  var userGuess = document.getElementById("guessText").value;
  var random = Math.ceil(Math.random() * 10);
  if (userGuess == random)
    document.getElementById("answer").innerHTML = "Correct!";
  else
    document.getElementById("answer").innerHTML = "Incorrect, answer was " + random;
}
<form>
  <label for="guess">Enter a number between 1 and 10</label><br>
  <input type="text" id="guessText" value="">
  <input type="button" value="Submit" onclick="guess()">
</form>
<p id="answer">ANSWER</p>
Lewis
  • 4,285
  • 1
  • 23
  • 36