0

I am trying to do a number guessing game that sets up a random number and the user inputs a number to guess the random number in the range of 1 to 100. I made an if else statement for three scenarios i.e. when the number entered is equal to the random number, or less or greater. However, it only brings up the statement of the else part at all guesses. Why is that so?

<h1>Number Guessing Game</h1>
    <p>We have selected a random number between 1 and 100. See if you can guess it in 10 turns or fewer. We'll tell you if your guess was too high or too low.</p>
    <p>Enter a Guess: <input type="text" id="theInput"> <button id="submitButton">Submit Guess</button></p>
    <p id="feedback"></p>
    <script type="text/javascript">
        var numberEntered = document.getElementById('theInput').value; 
        var randomNumber = Math.floor(Math.random()* 100);
        alert(randomNumber);
        const submitButton = document.getElementById('submitButton');
        const feedback = document.getElementById('feedback');
        submitButton.addEventListener("click", function () {
            
            if (randomNumber === numberEntered) {
                feedback.innerHTML = "Congratulations! You got it right!" + "<p><button>Start a new Game</button></p>";
            } else if (randomNumber < numberEntered) {
                feedback.innerHTML = "Last Guess was too low!";
            } else  { 
                feedback.innerHTML = "Last Guess was too high!";
            } 
            
        } )
    </script>
  • 2
    [Duplicate](https://google.com/search?q=site%3Astackoverflow.com+js+input+value+as+number) of [Input value is a string instead of a number](https://stackoverflow.com/q/27849944/4642212). – Sebastian Simon Mar 17 '21 at 11:54
  • (And it would have been even *more* confusing if the first comparison hadn't been strict :) – Dave Newton Mar 17 '21 at 11:57
  • @DaveNewton actually, a bit less, as the string would have been cast to a number automatically, so the equality would have just worked. Same with the relation operator. – VLAZ Mar 17 '21 at 11:59
  • @VLAZ Hm for some reason I thought the order of the comparison mattered; I must have fat-fingered something when I was testing in the console. Mea culpa. – Dave Newton Mar 17 '21 at 13:08

0 Answers0