-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
61 lines (44 loc) · 1.57 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
const charRange = {
uppercase: "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
lowercase: "abcdefghijklmnopqrstuvwxyz",
number: "0123456789",
symbol: "!@#$%^&*_+?",
};
const output = document.getElementById("output");
const length = document.getElementById("length");
const checkboxes = document.querySelectorAll('input[type="checkbox"]');
const generateButton = document.getElementById("generate");
const copyButton = document.getElementById("copy");
copyButton.addEventListener("click", copyPassword);
generateButton.addEventListener("click", generate);
length.addEventListener("change", generate);
checkboxes.forEach((checkbox) => checkbox.addEventListener("change", generate));
function generate() {
const len = parseInt(length.value);
if (len < parseInt(length.min) || len > parseInt(length.max)) {
output.textContent = "Invalid length";
return;
}
const checkedOptions = [...checkboxes].filter((checkbox) => checkbox.checked);
checkedOptions.map(
(checkbox) => (checkbox.disabled = 1 === checkedOptions.length)
);
output.textContent = createPassword(len, checkedOptions);
}
function createPassword(len, options) {
let charList = "";
options.forEach((option) => (charList += charRange[option.id]));
let password = "";
for (let i = 0; i < len; i++) {
password += charList.charAt(Math.floor(Math.random() * charList.length));
}
return password;
}
function copyPassword() {
const password = output.textContent;
if (!password) return;
navigator.clipboard.writeText(password).then(() => {
alert("Password copied to clipboard");
});
}
generate();