Vercity Official Vercity Official - 4 months ago 39
Javascript Question

Validate response from prompt(). Prompt again on invalid response

I want to make it so that if the user doesn't enter "1" or "2", the question must be re-answered. I tried

prompt{choice1};
but it doesn't work.

Any solutions?



var choice1 = prompt("You see a bear on your campsite, What do you do ? Type 1 if you start running into the woods or type 2 if you fight the bear.");

if (choice1 == "1") {

for (var i = 2; i < 3; i++) {
alert("You start running into the woods. You stop, Out of breathe and realize you somehow got cut in your left arm.");
}

} else if (choice1 == "2") {

for (var b = 0; b < 1; b++) {
alert("You look around you to find something that could help you fight off the bear. You see a rock and you pick it up. The bear is getting ready to attack and right away you throw the rock");
}

} else {}




Answer

Working fiddle

Use do..while loop :

do {
  var choice1 = prompt("You see a bear on your campsite, What do you do ? Type 1 if you start running into the woods or type 2 if you fight the bear.");

  if (choice1 == "1") {

    for (var i = 2; i < 3; i++) {
      alert("You start running into the woods. You stop, Out of breathe and realize you somehow got cut in your left arm.");
    }

  } else if (choice1 == "2") {

    for (var b = 0; b < 1; b++) {
      alert("You look around you to find something that could help you fight off the bear. You see a rock and you pick it up. The bear is getting ready to attack and right away you throw the rock");
    }

  }
}
while (choice1 != "1" && choice1 != "2");

Hope this helps.