パスワード表示

jquerys

チェックボックスをクリックでパスワードを表示するスクリプト。JQuery版とJavascript版。

 

html

<form method="POST" action="">
	<div class="form_parts">
		<input name="ID" type="text" placeholder="アカウント名"/>
	</div>
	<div class="form_parts">
		<input id="password" name="PW" type="password" placeholder="パスワード"/>
	</div>
	<div class="form_parts">
		<input type="checkbox" id="password-check" style="width:16px; height:16px;">
		パスワードを表示する
	</div>
	<div class="form_parts">
		<button type="submit" id="lbtn">ログイン</button>
	</div>
</form>

 

JQuery

$(document).ready(function() {
    const $pwd = $('#password');
    const $pwdCheck = $('#password-check');

    $pwdCheck.on('change', function() {
        $pwd.attr('type', function(_, attr) {
            return attr === 'password' ? 'text' : 'password';
        });
    });
});

 

Javascript

 const pwd = document.getElementById('password');
 const pwdCheck = document.getElementById('password-check');
 pwdCheck.addEventListener('change', function() {
     if(pwdCheck.checked) {
         pwd.setAttribute('type', 'text');
     } else {
         pwd.setAttribute('type', 'password');
     }
 }, false);