我有一个输入类型密码可以输入密码,还有一个显示密码复选框,可以将输入类型密码更改为文本,因此输入密码字符是可见的。还有一个“随机密码”按钮,用于使密码随机化,并在单击按钮时选中复选框以显示密码。
问题是,当单击随机密码按钮以触发JavaScript代码检查显示密码复选框时,onchange
复选框功能未触发/运行。这是我的代码
function togglePassword(checkbox) {
var x = document.getElementById("staff-password");
if (checkbox.checked == true){
x.type = "text";
} else {
x.type = "password";
}
}
function clickRandom(){
var randomPass = randomPass();
document.getElementById("staff-password").value(randomPass);
document.getElementById("show-password").checked = true;
}
function randomPass() {
var length = 6;
var text = "";
var possible = "3907154628";
for (var i = 0; i < length; i++){
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
<span> Password </span>
<input type="password" name="password" id="staff-password" maxlength="6" value="">
<br/>
<input type="checkbox" onchange="togglePassword(this)" id="show-password" >
<span style="margin-left:3px;">Show Password</span>
<br/>
<button type="button" id="random-password" onclick="clickRandom()">
<span>Random password</span>
</button>
答案 0 :(得分:1)
正确的是,对表单字段状态的动态更新不会导致用户交互中引发的典型事件。相反,您可以自己手动调用回调。
查看内嵌评论
function togglePassword(checkbox) {
var x = document.getElementById("staff-password");
if (checkbox.checked == true){
x.type = "text";
} else {
x.type = "password";
}
}
function clickRandom(){
// value is a property, you have to assign it a value:
document.getElementById("staff-password").value = randomPass();
document.getElementById("show-password").checked = true;
togglePassword(document.getElementById("show-password")); // Manually call the toggle function
}
function randomPass() {
var length = 6;
var text = "";
var possible = "3907154628";
for (var i = 0; i < length; i++){
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
<span> Password </span>
<input type="password" name="password" id="staff-password" maxlength="6" value="">
<br/>
<input type="checkbox" onchange="togglePassword(this)" id="show-password" >
<span style="margin-left:3px;">Show Password</span>
<br/>
<button type="button" id="random-password" onclick="clickRandom()">
<span>Random password</span>
</button>