I am new to JavaScript and I'm currently creating a password generator for a project. I am running into a problem where when the user is prompted with confirm
messages to select their ideal password criteria. I want to return an alert
message to the window with a loop
function if they don't choose at least one option. Here is what I have so far.
// function: when you click on generate button it prompts messages to select password criteria.
var generateBtnPrompt = function () {
var confirmNumber = confirm("Click 'OK' to generate numbers in your password");
var confirmLowerCase = confirm("Click 'OK' to generate lowerCase characters in your password");
var confirmUpperCase = confirm("Click 'OK' to generate upperCase characters in your password");
var confirmSymbols = confirm("Click 'OK' to generate symbols characters in your password");
//parseInt convert a string into an integer
var charLength = parseInt(prompt("How many characters would you like your password to be? Please choose a number from (8-128)"));
};
You can use the Logical OR
operator (||
) to check that at least one of the variables are true.
MDN Web Docs:
The logical OR (||
) operator (logical disjunction) for a set of operands istrue
if and only if one or more of its operands is true.
And recursion
to re-run the function if none of the variables are true.
Like this:
if (!(confirmNumber || confirmLowerCase || confirmUpperCase)) {
alert("You need to pick at least one!");
return generateBtnPrompt()
}
Full code:
var generateBtnPrompt = function () {
var confirmNumber = confirm("Click 'OK' to generate numbers in your password");
var confirmLowerCase = confirm("Click 'OK' to generate lowerCase characters in your password");
var confirmUpperCase = confirm("Click 'OK' to generate upperCase characters in your password");
var confirmSymbols = confirm("Click 'OK' to generate symbols characters in your password");
if (!(confirmNumber || confirmLowerCase || confirmUpperCase)) {
alert("You need to pick at least one!");
return generateBtnPrompt()
}
var charLength = parseInt(prompt("How many characters would you like your password to be? Please choose a number from (8-128)"));
};
generateBtnPrompt()