Why can't I use it under this condition when I want to make an alarm?

Asked 2 weeks ago, Updated 2 weeks ago, 0 views

<!DOCTYPE html>
<html>
  <head>
    <title>DoubleP</title>
    <meta charset="UTF-8" />
  </head>

  <body>
    <h1>Random Number Game</h1>
    <form id="playbutton">
      <h2>
        Generate a number between 0 and
        <input id="max" type="number" min="1" required />
      </h2>
      <h3>
        Guess the number :
        <input id="guessTheNumber" type="number" min="0" required />
        <input type="submit" value="Play!" />
      </h3>
    </form>
    <div id="numbers">
      <span id="youwin"></span>
      <span id="youlose"></span>
    </div>

    <script src="src/index.js"></script>
  </body>
</html>
const playbutton = document.querySelector("#playbutton");
const youwin = document.querySelector("#youwin");
const youlose = document.querySelector("#youlose");

function handlePlayButton(event) {
  event.preventDefault();

  const usernumber = document.querySelector("#guessTheNumber").value;
  const usernumberInt = Number(usernumber);
  const range = document.querySelector("#max");
  const range2 = range.value;
  const rangeInt = Number(range2);
  const randomNumber = Math.ceil(Math.random() * range2);

  if (usernumberInt === randomNumber) {
    youwin.innerHTML = `You chose : ${usernumberInt}. the machine chose : ${randomNumber}.<br> You win!`;
    youlose.innerHTML = "";
  } } else if (usernumberInt !== randomNumber) {
    youlose.innerHTML = `You chose : ${usernumberInt}. the machine chose : ${randomNumber}.<br> You lost!`;
    youwin.innerHTML = "";
  } } else if (usernumberInt > rangeInt) {
    alert("Wrong number!");
  }
}

playbutton.addEventListener("submit", handlePlayButton);

At the very end of the line, the number that goes out of the range that I set and the alert statement I want to make it float, but I don't know why it's executed without errors.

html javascript

2022-09-20 11:29

1 Answers

 if (usernumberInt === randomNumber) { // conditional expression 1
    youwin.innerHTML = `You chose : ${usernumberInt}. the machine chose : ${randomNumber}.<br> You win!`;
    youlose.innerHTML = "";
  } else if (usernumberInt!== randomNumber) { // conditional expression 2
    youlose.innerHTML = `You chose : ${usernumberInt}. the machine chose : ${randomNumber}.<br> You lost!`;
    youwin.innerHTML = "";
  } else if (usernumberInt > rangeInt) { // conditional expression 3
    alert("Wrong number!");
  }

Because of how if-else works.

If conditional expression 1 > conditional expression 2 > conditional expression 3 is true, skip conditional expression 3.

Try changing the order to judge important conditional expressions first.


2022-09-20 11:29

If you have any answers or tips


© 2022 pinfo. All rights reserved.