简体   繁体   中英

Using javascript to check if user has entered a correct value

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> 

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 (ie 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.

You need to get value of input , so replace

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

with

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

And you good to go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM