[Solved] Keep prompting the user a number until it falls into a certain range


I would use a do loop here, as we want to prompt the user in any case right at the start. So it’s a bit more logical if we don’t do the validity check as the first thing, but as the last thing in the loop.

Next I would recommend using a flag variable that can be true or false, depending on the user’s input. This makes the code easier to read and helps reduce the chance of bugs.

We also need to break the loop when the user clicks “cancel” in the prompt.

var choice = 0;
var price = 50;
var isValid = false;

do {
    choice = prompt("Please input number of days for your Bus tour","");
    if (choice === null) break;  // user clicked "cancel"

    choice = parseInt(choice);
    isValid = choice >= 1 && choice <= 20;

    if (isValid) {
        alert("Your total price for your bus tour is "+(choice*price));
    } else {
        alert("You cannot have a bus tour for less than 1 day or over 20 days!");
    }
} while ( !isValid );

1

solved Keep prompting the user a number until it falls into a certain range