![](/img/trans.png)
[英]The messages are not properly being displayed on my webpage in javascript. The message only displays after clicking in and out of the textbox twice.
[英]Why are my messages not being displayed when I click out of the textbox on my webpage?
我編寫了幾個函數來檢查兩個密碼是否相等。 當我從“驗證密碼”框中單擊時,它應該顯示“密碼匹配”或“由於兩個密碼不匹配,請再次輸入密碼”,具體取決於密碼是否相等。 但是,當我輸入兩個相同或兩個不同的密碼,然后單擊“驗證密碼”文本框之外時,根本不會顯示該消息。 我在這里做錯了什么?
這就是作業的要求:網頁應具有兩個類型為“密碼”的輸入框。 用戶將需要在第一個輸入框中輸入新密碼,然后在第二個輸入框中再次鍵入密碼。
當焦點離開第二個框時,腳本將檢查以確保兩個框的值相同且不為空(5分)。 注意:Internet上的許多示例都使用html文件中的html input onchange屬性來調用事件處理程序。 不要使用任何類型的html屬性來處理事件。 而是在.js文件中定義一個事件偵聽器(5分)。
如果它們不同,則顯示一條消息,提示需要再次嘗試,然后在第一個密碼框中重置焦點。 如果它們是相同的,同一個消息,說的密碼匹配替換任何先前的錯誤消息。
我正在為此網頁使用password.js文件和setpassword.html文件。
我的password.js文件是:
var password1 = document.getElementById("txtPassword").value;
var verifypassword = document.getElementById("txtPWVerified").value;
var verifypasswordclick = document.getElementById("txtPWVerified");
function verifypassword1() {
if(password1 == verifypassword && password1 != "" && verifypasword != "") {
alert('The passwords match');
}
else if(password1 != verifypassword || password1 == "" || verifypasword == "") {
alert("Please enter your password again because the two passwords don't match");
}
}
verifypasswordclick.onblur = function() {
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>
您沒有正確調用verifypassword1
函數。 您需要括號。 但是,您可以嘗試使用此行,而不是從匿名函數中調用該函數。
verifypasswordclick.addEventListener("blur",verifypassword1);
另外,您每次都在比較初始值。 每次檢查密碼時,都需要從input
元素中獲取新值。 在您的verifypassword1
函數中,您需要像這樣從這些input
元素獲取新值。
function verifypassword1() {
password1 = document.getElementById("txtPassword").value;
verifypassword = document.getElementById("txtPWVerified").value;
// rest of code
}
代替此verifypasswordclick.onblur = function() { verifypassword1;}
這樣做verifypasswordclick.onblur = verifypassword1;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.