Reputation: 181
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>
Upvotes: 0
Views: 691
Reputation: 447
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.
Upvotes: 2
Reputation: 11601
You need to get value of input
, so replace
if (parseInt(userGuess) === randomNumber) {
with
if (parseInt(userGuess.value) === randomNumber) {
And you good to go.
Upvotes: 0