登入表單中,使用者希望檢視剛輸入的密碼是否正確,提供「顯示密碼」勾選框或按鈕切換 type="password" ↔ type="text"。
<label>
<input type="password" id="pwd" value="523654" />
<button type="button" id="toggleBtn">顯示密碼</button>
</label>
<script>
const input = document.getElementById('pwd');
const btn = document.getElementById('toggleBtn');
btn.addEventListener('click', () => {
const isPwd = input.type === 'password';
input.type = isPwd ? 'text' : 'password';
btn.textContent = isPwd ? '隱藏密碼' : '顯示密碼';
});
</script>
$('#toggleBtn').click(function() {
var $pwd = $('#pwd');
if ($pwd.attr('type') === 'password') {
$pwd.attr('type', 'text');
$(this).text('隱藏密碼');
} else {
$pwd.attr('type', 'password');
$(this).text('顯示密碼');
}
});
注意:IE9 以下不支援動態修改 type 屬性,需採用「建立新 input 替換」或「雙 input 切換顯示」方案。
<span id="pwdWrap">
<input type="password" id="pwd1" value="523654" />
<input type="text" id="pwd2" value="523654" style="display:none" />
</span>
<button id="toggleBtn">顯示密碼</button>
<script>
$('#toggleBtn').click(function() {
var $p1 = $('#pwd1'), $p2 = $('#pwd2');
if ($p1.is(':visible')) {
$p2.val($p1.val()).show(); $p1.hide();
$(this).text('隱藏密碼');
} else {
$p1.val($p2.val()).show(); $p2.hide();
$(this).text('顯示密碼');
}
});
</script>
type="password"),避免肩窺洩露。input.focus()。autocomplete="current-password" 協助瀏覽器自動填充。