'JavaScript: Generating a random number with user input from a prompt box (number guess game)

The user has to guess a randomly generated number based on the highest value THEY input into a prompt box. Example (from 1 to ?) I have to use a prompt and the value cannot be a decimal or string. I'm not sure how to validate that or just not allow the user to input an invalid entry.

I am having issues reusing the number they input in the function for random number generation let num = Math.floor(Math.random() * inputMaxNumber + 1); in the game. I tried converting the value from a string to a number but that didn't work either. This is what I have so far:

//prompt for max number the user inputs 
function maxNumber() {

    let inputMaxNumber = prompt ("Enter the maximum number the game can pick", " #");
    if ( inputMaxNumber > 1) {
        document.getElementById("maxNumber").innerHTML = "Guess a number between 1 and " + inputMaxNumber; 

        }
    else {
        alert("You must enter a positive whole number greater than 1");
    }

    console.log(inputMaxNumber);

}

inputMaxNumber = Number(document.getElementById("maxNumber").value); //converts this to a number from a string

// array that stores guesses
var numGuessArray = []



//validates user input for guesses (no decimals, strings, or negative numbers)
function onlyNumbers(num){
    if ( /[^0-9]+/.test(num.value) ){
       num.value = num.value.replace(/[^0-9]*/g,"")
    }
 }

//get user input to use in random number generation


// random value generated based on user input (a) new variable is num
let num = Math.floor(Math.random() * inputMaxNumber + 1);

console.log(num);
//counts the number of guesses for correct guess
var guess = 1;

//store counts and numbers guess in an array (don't count invalid guesses)

function do_guess() {


    let guess = Number(document.getElementById("guess").value); //converts this to a number from a string

    let message = document.getElementById("message");

    //show on console
    console.log(guess);

    //hints about guess

    if(guess == num) { //correct guess with count
        message.innerHTML = "You got it and it took " + guess + " guess!";
    }
    else if (guess > num) { //number too high
         message.innerHTML = "No, try a lower number";
    }
    else {//number too low
        message.innerHTML = "No, try a higher number";
    }

    //you already guessed that number NO COUNT

}
//guess button used to guess
//use an array to keep track of the guess
 <div class="container">
    <h1>Higher - Lower</h1>
        <p>Guess a number</p> 
        <div class = "row">
            <div class ="col-lg-3 col-md-6"> 
                <form>
                <div class ="form-group">
                    <!-- This button triggers the prompt to allow the user to enter the max number-->
                    <input type ="button" value = "Click To Start" onclick = "maxNumber()";/>
                </div>


                <div class ="form-group">
                    <label> Your Guess:</label>
                    <!-- Prevents user from inputing decimals with onkeyup-->
                    <input type ="text" onkeyup="onlyNumbers(this)" id="guess" class ="form-control"> 
                </div>


                <p id = "maxNumber" ></p><!--Outputs maximum number range the user selected-->
                <!--Button calls guess funciton when clicked-->
                <button type="button" class ="btn btn-primary" onclick = "do_guess()">Guess</button> 
            </form>
        </div>
    </div>
        <p id="message"></p> <!--Where message will go-->
    </div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>


Solution 1:[1]

Inside function maxNumber() you define inputMaxNumber locally let inputMaxNumber = prompt(...); so its value is lost when the function execution ends.

Additionally, the code where you generate the random number is executed only once, upon page load let num = Math.floor(...);. It's not executed after user enters his choice for the maximum.

Solution:

  1. define num globally
  2. assign the random value to it inside maxNumber()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Petr 'PePa' Pavel