0

I am trying to make a number guessing game where a random number between 1-50 is selected, and the user has to guess it. I am currently stuck where regardless if the user enters a right or wrong answer, my WRONG alert pops up. I am wondering where I went wrong, any help is appreciated.

var randomNumber = Math.floor(Math.random() * 50) + 1;
console.log(randomNumber);
var userGuess = document.querySelector("#guess");
document.getElementById("submit").addEventListener("click", submit, false);

function submit() {

  if (parseInt(userGuess) === randomNumber) {
    alert("You Win");
  } else {
    alert("You Lose");
  }
}
<input id="guess" type="text">
<br />
<button id="submit" type="submit">Guess 1</button>
<button id="submit2" type="submit">Guess 2</button>
<button id="submit3" type="submit">Guess 3</button>
<p id="result"></p>
<p id="hotCold"></p>
<h2>Your guesses</h2>
<p id="prevGuesses"></p>

2
  • userGuess is an element, parsing an element to number returns NaN, which is not equal even with itself. Commented Sep 18, 2017 at 4:13
  • note: when you submit a form, a new page is loaded Commented Sep 18, 2017 at 4:17

2 Answers 2

2

You are calling parseInt on the actual <input> element, not the inputted value (which will return NaN). The actual inputted string is in the value property of the element, so replace this:

if (parseInt(userGuess) === randomNumber)

with this:

if (parseInt(userGuess.value) === randomNumber)

and it should work.

Note that making the userGuess variable be initialized with the value (i.e. var userGuess = document.querySelector("#guess").value instead of var userGuess = document.querySelector("#guess")) will not work, as while DOM elements are dynamically updated, the value property is a simple string, and so userGuess will be set to an empty string (the starting value of the <input>) and will not be updated when the user inputs a number.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, this worked! I knew I was missing something simple. Appreciate the note as well, good to know.
0

You need to get value of input, so replace

if (parseInt(userGuess) === randomNumber) {

with

if (parseInt(userGuess.value) === randomNumber) {

And you good to go.

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.