Javascript alert wont dismiss (while loop)

160 Views Asked by At

I'm trying to make a "How many fingers are you holding up" page, if i input 1-5 in the box, it works, but if i input more than 5, the alert wont disappear, can anyone help me with this? Sorry for the noob question Any help will be greatly appreciated! Thanks!!

document.getElementById("guess").onclick = function() {

  var gotIt = false;
  var guesess = 1;
  var x;

  while (gotIt == false) {
    x = Math.random();
    x = 6 * x;
    x = Math.floor(x);

    if (document.getElementById("myNumber").value == x) {
      gotIt = true;
    } else {
      if (guesess == 20) {
        alert("i give up");
      } else {
        guesses++;
      }
    }
  }
  alert("I got it! It was a " + x + "It only took me " + guesess + "guesses");
}
<p>How many fingers are you holding up?</p>
<input id="myNumber" />
<button id="guess">Guess!!</button>

2

There are 2 best solutions below

0
On BEST ANSWER

First issue, fix your typo: you use a mix of guesess and guesses they must all be the same.

Second issue, once the code is 'giving up', it isn't setting the flag to break the loop. You can use break after the alert to break the loop:

alert("i give up");
break;

Third issue, you will want a check to ensure you don't display the "i got it" message if no match is found (i.e. gotIt is still false):

if (gotIt) 
    alert("I got it! It was a " + x + "It only took me " + guesess + "guesses");

(alternatively you can put this alert inside the same if block that sets gotIt = true)

Here is a working example

0
On

it is good idea to convert the input you you can try replacing your java script code so that you can control conversion problems, and place your

alert("I got it! It was a " + x + " It only took me " + guesess + "guesses");

inside the if(x == n), because the alert will be popped out when the random number matches the input keyed, try this code:

document.getElementById("guess").onclick = function() {
  var gotIt = false;
  var guesess = 1;
  var x;
  var num=parseInt(document.getElementById('myNumber').value);

  while (gotIt == false) {
    x = Math.random();
    x = 6 * x;
    x = Math.floor(x);

    if (x == num) {
      gotIt = true;
        alert("I got it! It was a " + x + " It only took me " + guesess + "guesses");
    } else {
      if (guesess == 20) {
        alert("i give up");
          break;
      } else {
        guesess++;
      }
    }
  }

}