方法1
type属性をsetAttributeメソッドで切り替えています。
HTML
1<!DOCTYPE html>
2<html lang="ja">
3<head>
4 <meta charset="UTF-8">
5 <title>タイトル</title>
6 <style type="text/css">
7 * {
8 margin: 0;
9 padding: 0;
10 }
11 </style>
12</head>
13<body>
14<form action="">
15 <label for="password1">
16 <input type="password" id="password1">
17 </label>
18 <label>
19 <input type="checkbox" id="togglePassword">
20 </label>
21</form>
22<script>
23 document.addEventListener("DOMContentLoaded", function () {
24 if (document.getElementById("togglePassword").checked) {
25 document.getElementById("password1").setAttribute("type", "text");
26 } else {
27 document.getElementById("password1").setAttribute("type", "password");
28 }
29 });
30
31 document.getElementById("togglePassword").addEventListener("change", function () {
32 if (this.checked) {
33 document.getElementById("password1").setAttribute("type", "text");
34 } else {
35 document.getElementById("password1").setAttribute("type", "password");
36 }
37 });
38</script>
39</body>
40</html>
方法2
予めテキストボックスを2つ用意しておいて、displayプロパティで切り替えています。
HTML
1<!DOCTYPE html>
2<html lang="ja">
3<head>
4 <meta charset="UTF-8">
5 <title>タイトル</title>
6 <style type="text/css">
7 * {
8 margin: 0;
9 padding: 0;
10 }
11 </style>
12</head>
13<body>
14<form action="">
15 <label for="password1">
16 <input type="password" id="password1">
17 </label>
18 <label for="password2">
19 <input type="text" id="password2">
20 </label>
21 <label>
22 <input type="checkbox" id="togglePassword">
23 </label>
24</form>
25<script>
26 document.addEventListener("DOMContentLoaded", function () {
27 if (document.getElementById("togglePassword").checked) {
28 document.querySelector("label[for='password1']").style.display = "none";
29 document.querySelector("label[for='password2']").style.display = "block";
30 } else {
31 document.querySelector("label[for='password1']").style.display = "block";
32 document.querySelector("label[for='password2']").style.display = "none";
33 }
34 });
35
36 document.getElementById("password1").addEventListener("input", function () {
37 document.getElementById("password2").value = this.value;
38 });
39
40 document.getElementById("password2").addEventListener("input", function () {
41 document.getElementById("password1").value = this.value;
42 });
43
44 document.getElementById("togglePassword").addEventListener("change", function () {
45 if (this.checked) {
46 document.querySelector("label[for='password1']").style.display = "none";
47 document.querySelector("label[for='password2']").style.display = "block";
48 } else {
49 document.querySelector("label[for='password1']").style.display = "block";
50 document.querySelector("label[for='password2']").style.display = "none";
51 }
52 });
53</script>
54</body>
55</html>
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。