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>
First issue, fix your typo: you use a mix of
guesess
andguesses
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: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):(alternatively you can put this alert inside the same if block that sets
gotIt = true
)Here is a working example