我写了几个函数来检查两个密码是否相等。我先输入两个密码。当我点击"验证密码"框时,它应该显示"密码匹配"或"需要再次尝试。请在第一个密码框中再次输入您的密码,因为两个密码不匹配",这取决于密码是否相等。如果两个密码不相等,则会显示消息"需要再次尝试。由于两个密码并不匹配,请在第一个密码框中再次输入您的密码"。当两个密码不匹配时,我还希望第一个密码框(password1)变为空(我希望它重置)。但是,这在我的代码中不起作用。我在这里做错了什么?
我使用了一个password.js文件和一个setpassword.html文件。
我的password.js文件是这样的:
var verifypasswordclick = document.getElementById("txtPWVerified");
function verifypassword1() {
var password1 = document.getElementById("txtPassword").value;
var verifypassword = document.getElementById("txtPWVerified").value;
if(password1 == '' || verifypassword == '') {
return null;
}
if(password1 == verifypassword) {
alert('The passwords match');
}
if(password1 !== verifypassword || password1 == "" || verifypasword == "") {
alert("A second try is needed. Please enter your password in the first password box again because the two passwords don't match");
}
if(password1 !== verifypassword || password1 == "" || verifypasword == "") {
password1 = "";
}
}
verifypasswordclick.addEventListener("blur",verifypassword1);
我的setpassword.html文件是这样的:
<!DOCTYPE html>
<!-- H5FormValidation.html -->
<html lang="en">
<head>
<meta charset="utf-8">
<title>Register Here</title>
</head>
<body>
<h2>Register Here</h2>
<form id="formTest" method="get" action="processData">
<table>
<tr>
<td><label for="txtEmail">Email<span class="required">*</span></label></td>
<td><input type="email" id="txtEmail" name="email" required></td>
</tr>
<tr>
<td><label for="txtPassword">Password<span class="required">*</span></label></td>
<td><input type="password" id="txtPassword" name="password" required></td>
</tr>
<tr>
<td><label for="txtPWVerified">Verify Password<span class="required">*</span></label></td>
<td><input type="password" id="txtPWVerified" name="pwVerified" required></td>
</tr>
<tr>
<td> </td>
<td>
<input type="reset" value="CLEAR" id="btnReset"></td>
</tr>
</table>
</form>
<script src = "password.js"></script>
</body>
</html>
您只需要设置password元素的值(由于元素的id)
document.getElementById("txtPassword").value = '';
按如下方式更改password.js代码。
var verifypasswordclick = document.getElementById("txtPWVerified");
function verifypassword1() {
var password1 = document.getElementById("txtPassword")
var verifypassword = document.getElementById("txtPWVerified");
//do nothing until the fields is field
if(password1.value && verifypassword.value){
if(password1.value === verifypassword.value) {
alert('The passwords match');
}else{
alert("A second try is needed. Please enter your password in the first password box again because the two passwords don't match");
password1.value= "";
}
}
}
verifypasswordclick.addEventListener("blur",verifypassword1);