【发布时间】:2018-11-07 17:49:53
【问题描述】:
我正在创建一个密码字段,用户可以在其中隐藏/显示他正在输入的密码。下面是html和javascript代码。问题是当我在浏览器中测试代码时:- 我输入密码并单击“显示/隐藏”按钮,密码可见,页面刷新,然后密码消失。我该如何解决这个问题?
html:
<html>
<head>
<meta charset="utf-8" />
<title> Page Title </title>
<meta name ="viewport" content="width= device-width, initial-scale=1">
<script src="main.js"></script>
</head>
<body>
<form action="">
<input type="text" name="uid" placeholder="Username">
<input id="loginPwdChange" type="password" name="pwd" placeholder="Password">
<button onclick="changePwdView()"> Show/Hide </button>
<button type="submit" name="submit"> Login </button>
</form>
</body>
</html>
JS:
let loginPwdStatus = false;
function changePwdView(){
let getLoginInput = document.getElementById("loginPwdChange");
if(loginPwdStatus === false){
getLoginInput.setAttribute("type", "text");
loginPwdStatus = true;
}else if(loginPwdStatus === true){
getLoginInput.setAttribute("type", "password");
loginPwdStatus = false;
}
}
【问题讨论】:
-
除了 type="button",您可以用一行替换所有 if/then/else 块:getLoginInput.type = getLoginInput.type === 'text' ? '密码' : '文本';
-
@BlackCat 您需要将表单提交回服务器吗?
-
暂时不需要
标签: javascript html forms passwords