03. Toggling passwords in multiple forms

Change Username

Enter your username and password to change your username.

Change Password

Enter your current password and new password below.

HTML

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
<h2>Change Username</h2>

<p>Enter your username and password to change your username.</p>

<form>
<div>
<label class="label" for="username">Username</label>
<input autocomplete="off" class="input" type="text" name="username" id="username">
</div>
<div>
<label class="label" for="password">Password</label>
<input autocomplete="off" class="input" type="password" name="password" id="password">
</div>
<div>
<label class="label" for="show-password">
<input class="checkbox" type="checkbox" name="show-password" id="show-password" data-pw-toggle="#password">
Show password
</label>
</div>
<p>
<button class="button" type="submit">Change Username</button>
</p>
</form>

<h2>Change Password</h2>

<p>Enter your current password and new password below.</p>

<form>
<div>
<label class="label" for="current-password">Current Password</label>
<input autocomplete="off" class="input" type="password" name="current-password" id="current-password">
</div>
<div>
<label class="label" for="new-password">New Password</label>
<input autocomplete="off" class="input" type="password" name="new-password" id="new-password">
</div>
<div>
<label class="label" for="show-passwords">
<input class="checkbox" type="checkbox" name="show-passwords" id="show-passwords"
data-pw-toggle="#current-password, #new-password">
Show passwords
</label>
</div>
<p>
<button class="button" type="submit">Change Passwords</button>
</p>
</form>

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/* In the first form, the #show-password checkbox should toggle 
the #password field visibility. In the second form, the #show-passwords checkbox
should toggle the visibility of the #current-password and #new-password fields. */

document.addEventListener('click', function (e) {
if (!e.target.matches('[data-pw-toggle]')) return;

const passwords = Array.prototype.slice.call(document.querySelectorAll(
e.target.getAttribute('data-pw-toggle')));

passwords.forEach(password => {
if (e.target.checked) {
password.type = 'text';
} else {
password.type = 'password';
}
})
});