'how to use while loop on a prompt in Javascript
[
let welcome;
welcome = "Welcome to my first COMP1231 Program.";
alert(welcome)
let name;
name =(prompt("Please enter your name:?", "Tafadzwa Marisa" ));
let program;
program =(prompt("Please enter your Program:?", "COMP1231" ));
]1 So l am trying to use a prompt which asks a user for their name and when the user enters a name it proceeds to another prompt but when the user doesn't enter anything it loops back to the first prompt which is ask for the users name. If the user enters a valid input it then goes to the program prompt where if the user enters any input it proceeds but if the user doesn't it loops to the same prompt. I want to use the while loop for this
Solution 1:[1]
You can create a function which will basically execute a while loop until user enters some input. This function returns the input value if it's not empty.
function loopUntilNonEmptyInput(prompt_ques, default_inp) {
let retval;
while (true) {
retval = (prompt(prompt_ques, default_inp));
if (retval !== '')
return retval;
alert("Empty input, please re-try");
}
}
let welcome;
welcome = "Welcome to my first COMP1231 Program.";
alert(welcome);
let name = loopUntilNonEmptyInput("Please enter your name:?", "Tafadzwa Marisa");
let program = loopUntilNonEmptyInput("Please enter your Program:?", "COMP1231");
console.log(name, program);
Solution 2:[2]
so after researching l was finally able to find the best suitable way. Thank you for you suggestions and your help. My issue was mainly on how l was arranging the year value as a string for while loop as l was using (year<1&&year>3)which was causing the error. After getting an idea on what not to put l finally figured it out
let year;
// taking year value as string
year =(prompt("Please enter your year of study:", "1"));
// loop will continue until user 1 or 2 or 3
while(parseInt(year) <1 || parseInt(year) > 3 || year=== ""){
// again taking year as string
year = (prompt("Please enter your year of study:", "1"));
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | kiner_shah |
| Solution 2 | Tafadzwa Marisa |
