Home > front end >  How do you prompt a user and have conditional validation in a loop for a function?
How do you prompt a user and have conditional validation in a loop for a function?

Time:06-30

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Higher Lower</title>
  </head>

  <body>
    <h1>Higher - Lower</h1>

    <!--maxNum Function-->
    <!-- <p>Please enter a maximum number:</p>
    <input type="text" id="maxNum" /><br /><br /> -->
    <button onclick="userInput()">Input maximum number</button>

    <p id="ranNum"></p>

    <p id="validation"></p>

    <!--higherLower Function-->
    <p>Your Guess:</p>
    <input type="text" id="choice" /><br /><br />
    <button onclick="higherLower()">Guess</button>

    <p id="result"></p>

    <p id="values"></p>
  </body>
  <script src="scripts.js"></script>
</html>
function userInput() {
    let userMax=prompt("Please enter a maximum number:");
    window.alert(userMax);

    while (userMax < 1 || userMax == isNaN()) {
        alert("Maximum number cannot be negative, zero, or non-numbers");
        userInput();
    }

    // Declares new maximum number
    // let userMax=prompt("Please enter a maximum number:");
    //var userMax=document.getElementById("maxNum").value;
    // window.alert(userMax);

    if(userMax>=1) {
        alert("Maximum number set to "   userMax);
    }
    // else if(userMax<1) {
    //     alert("Maximum number cannot be lower than 1. Please try again!");
    // }
    // else if(userMax=isNaN()) {
    //     alert("Maximum number must be numeric. Please try again!");
    // }
}

function isFloat(userMax) {
    return Number(userMax) === n && n % 1 !== 0;
}

function higherLower(choice) {
    // Declares random number variable
    var randomNumber=Math.floor(Math.random() * 20)   1;
    window.alert(randomNumber);
    // Declares user guess variable
    var guess=document.getElementById('choice').value;
    
    // Declares random number variable
    if(randomNumber==guess) {
        document.getElementById("result").innerHTML = "You got it!";
    }
    else if(randomNumber>=guess) {
        document.getElementById("result").innerHTML = "No, try a higher number.";
    }
    else if(randomNumber<=guess) {
        document.getElementById("result").innerHTML = "No, try a lower number.";
    }
}

I am creating a simple number guessing game and finding difficulty prompting the user in a conditional loop. The loop should continue as long as the following user input conditions are met: -zero -negative number -non number

I have messed around with while and do-while loops for quite a while trying to figure this out but perhaps I am missing something small to get this to work. As a side note, I am also having difficulty finding a way to auto round-up a decimal user input.

CodePudding user response:

There are a few things that I changed.

isNan is a function that requires the value to be passed to it: isNan(userMax)

I declared userMax outside of the function so that it can be used elsewhere.

I got rid of the alerts. I added userMax to the random number generator to be the highest number generated.

I also updated the function to return the value from prompt.

let userMax;
function userInput() {
    userMax = prompt("Please enter a maximum number:");
   
    while (userMax < 1 || isNaN(userMax)) {
        alert("Maximum number cannot be negative, zero, or non-numbers");
        userMax = userInput();
    }

    return Math.round(userMax);
}

function isFloat(userMax) {
    return Number(userMax) === n && n % 1 !== 0;
}

function higherLower(choice) {
    // Declares random number variable
    var randomNumber=Math.floor(Math.random() * userMax)   1;
    window.alert(randomNumber);
    // Declares user guess variable
    var guess=document.getElementById('choice').value;
    
    // Declares random number variable
    if(randomNumber==guess) {
        document.getElementById("result").innerHTML = "You got it!";
    }
    else if(randomNumber>=guess) {
        document.getElementById("result").innerHTML = "No, try a higher number.";
    }
    else if(randomNumber<=guess) {
        document.getElementById("result").innerHTML = "No, try a lower number.";
    }
}
<h1>Higher - Lower</h1>

    <!--maxNum Function-->
    <!-- <p>Please enter a maximum number:</p>
    <input type="text" id="maxNum" /><br /><br /> -->
    <button onclick="userInput()">Input maximum number</button>

    <p id="ranNum"></p>

    <p id="validation"></p>

    <!--higherLower Function-->
    <p>Your Guess:</p>
    <input type="text" id="choice" /><br /><br />
    <button onclick="higherLower()">Guess</button>

    <p id="result"></p>

    <p id="values"></p>

CodePudding user response:

First you need to wrap everything in a if you want real built-in validation (I know you didn't ask for built-in validation but bear with me). Real validation happens when a "submit" event is fired on a <form>. The normal behavior involves validation, collecting and sending data to a server, etc.

Figure I shows the minimal requirements in HTML needed to meet all conditions needed in OP:

Figure I

<form>
  <input type='number' min='1' max='100' step='1' required><button>Submit</button>
</form>

Details are commented in example

// Reference <form>
const hilo = document.forms.hilo;
// Generate a random number in the range of 1 to 100
let NUMBER = Math.floor(Math.random() * 100   1)   1;
console.log(NUMBER);
// Define counter value
let count = 0;
// Bind "submit" event to <form>
hilo.onsubmit = guessNumber;

/*
Event handlers pass Event Object by default
Stop the <form> from sending data to a server
Reference all form controls (IO)
Get the value of input#guess and convert it into an integer
Determine message to display in output#message
Increase the value of output#score by 1
*/
function guessNumber(e) {
  e.preventDefault();
  const IO = this.elements;
  let guess = parseInt(IO.guess.value);
  let message = guess > NUMBER ? `Lower` : guess < NUMBER ? `Higher` : `${NUMBER}! You win!`;
  IO.message.value = message;
  IO.score.value =   count;
}
// Bind <form> to the "reset" event
hilo.onreset = restartGame;

/*
Reference all form controls
Reset output#message to initial value
Reset output#score to 0
Get a new NUMBER to guess
*/
function restartGame(e) {
  const IO = this.elements;
  IO.message.value = `Guess a Number in the Range of 1 to 100`;
  IO.score.value = 0;
  NUMBER = Math.floor(Math.random() * 100   1)   1;
  console.log(NUMBER);
}
html {
  font: 300 2ch/1 'Segoe UI'
}

p {
  margin: -2px 0 8px
}

input,
button {
  display: inline-block;
  font: inherit
}

input {
  width: 6ch;
  text-align: center;
}

button {
  cursor: pointer;
  padding-bottom: 3px
}

#score {
  margin-left: 12px;
}

#score::after {
  content: ' Guesses'
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Higher Lower</title>
</head>

<body>
  <form id='hilo'>
    <fieldset>
      <legend>HiLo</legend>
      <p><output id='message'>Guess a Number in the Range of 1 to 100</output></p>
      <input id='guess' type='number' min='1' max='100' step='1' required>
      <button>Guess</button><button type='reset'>Reset</button>
      <output id='score'>0</output>
    </fieldset>
  </form>
</body>

</html>

  • Related