简体   繁体   中英

Looping prompt in Javascript until condition is met

I'm trying to use a while loop in order to show a prompt message that prompts the user for a number between 1 and 100. I want the code to execute a loop until the user enters a correct number (between 1 and 100) and after that, it should execute the function createGrid(parseInt(message)) ;

My code is working when I type a correct number (between 1 and 100) and it shows the alert when the number is greater than 100 or less than 1, but then if try to enter another number between 1 and 100 it keeps showing the alert even if the number is correct.

There is definitely an error in my while loop but I don't know how to fix it.

Here is the code:

function clearGrid() {
    while (container.firstChild) {
        container.firstChild.remove();
    }

    let input;
    let message = prompt('Enter the number of squares for each side of the new grid:');

    if (parseInt(message) < 1 || parseInt(message) > 100) {
        input = false;

    while (input === false) {
        alert('Please enter a valid number between 1 and 100.');
        message = prompt('Enter the number of squares for each side of the new grid:');
    }

    if (parseInt(message) > 1 || parseInt(message) < 100) {
        createGrid(parseInt(message));
    }
}

Well first of all you need to have && not || how you have it setup is that if the int is bigger than 1 its good (meaning that it can go from 1 to 10000000000) or it could be (100- -10000000000) meaning you have all the numbers optional.

also the 2 ifstatements, please just have the first and then else, its kinda confusing to look at 2 if statements that are doing the same thing.

here is what I would do

if ( 0 < parseInt(message) < 100) {
    createGrid(parseInt(message));
   
}
else{
    input = false;
    while (input === false) {
        alert('Please enter a valid number between 1 and 100.');
        message = prompt('Enter the number of squares for each side of the newgrid:');
} }

I cant see anything else wrong with the code, I think you might have not sent all the code here so here you go.

EDIT You are missing bracket on the if statement? are you not getting an error there?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM