Listing 2: The generate Function
// Executes when the Generate Passwords button is clicked.
function generate() {
var chars, len, num, m, n, pwds, pwd;
// Build a string based on the check boxes.
chars = "";
if (id("uppercase").checked) chars += UPPER_CHARS;
if (id("lowercase").checked) chars += LOWER_CHARS;
if (id("numbers").checked) chars += NUMBER_CHARS;
if (id("symbols").checked) chars += SYMBOL_CHARS;
// Complain if none of the check boxes are selected.
if (chars == "") {
window.alert("Select at least one character class.");
id("uppercase").focus();
event.returnValue = false;
return;
}
// Parse the password length field as base 10 number. Complain
// if the value is not a number or outside the allowed range.
len = parseInt(id("len").value, 10);
if (isNaN(len) || (len < 1) || (len > MAX_PASSWORD_LENGTH)) {
window.alert("Enter a number in the range 1 to " +
MAX_PASSWORD_LENGTH + ".");
event.returnValue = false;
id("len").focus();
return;
}
// Parse the number of passwords field as a base 10 number. Complain
// if the value is not a number or outside the allowed range.
num = parseInt(id("num").value, 10);
if (isNaN(num) || (num < 1) || (num > MAX_PASSWORD_NUMBER)) {
window.alert("Enter number in the range 1 to " +
MAX_PASSWORD_NUMBER + ".");
event.returnValue = false;
id("num").focus();
return;
}
// Clear the list of passwords.
id("passwords").value = "";
// The pwds variable will contain a newline-delimited list of
// random passwords. The code generates a random password, stores
// it in the pwd variable, and appends it to the pwds variable.
pwds = "";
for (m = 0; m < num; m++) {
// Begin Callout A
pwd = "";
for (n = 0; n < len; n++)
pwd += chars.charAt(Math.floor(Math.random() * chars.length));
// End Callout A
// Begin Callout B
pwds += pwds == "" ? pwd : "\n" + pwd;
// End Callout B
}
// Update the password list and enable the Copy to Clipboard and
// Clear List buttons.
// Begin Callout C
id("passwords").value = pwds;
id("copydata").disabled = false;
id("clear").disabled = false;
// End Callout C
}