我的Javascript函数有问题。它应该使用if
语句检查表单中的两个输入框是否具有相同的值。
HTML:
<form action="confirm_account.php" method="post" id="form" onsubmit="checkpassword()">
<p style="font-family:latine;">Password: <input type="password" name="password" id="password" style="font-family:latine;" required>
</p>
<br><br>
<p style="font-family:latine;">Re-enter Password: <input type="password" name="password-reenter" id="password-reenter" style="font-family:latine;" required> </p>
<span id="password-warning" style="color:red; font-weight:bold;"></span>
使用Javascript:
var password = document.getElementById("password").value;
var password2 = document.getElementById("password-reenter").value;
function checkpassword(){
if('password' == 'password2'){
document.getElementById("form").action = "confirm_account.php";
document.getElementById("password-warning").innerHTML = "";
}
else{
document.getElementById("password-warning").innerHTML = "The passwords do not match, please re-enter the password.";
document.getElementById("form").onsubmit = "return false";
}
};
警告消息显示,但onsubmit
未被修改。
答案 0 :(得分:2)
试试这个,它应该有效:
function checkpassword() {
var password = document.getElementById("password").value;
var password2 = document.getElementById("password-reenter").value;
if (password === password2) {
document.getElementById("form").action = "confirm_account.php";
document.getElementById("password-warning").innerHTML = "";
document.getElementById("password-success").innerHTML = "The passwords match! Well done!";
} else {
document.getElementById("password-warning").innerHTML = "The passwords do not match, please re-enter the password.";
document.getElementById("password-success").innerHTML = "";
document.getElementById("password-reenter").focus();
return false;
}
}
&#13;
<form action="#" method="post" id="form" onsubmit="return checkpassword()">
<p style="font-family:latine;">Password:
<input type="password" name="password" id="password" style="font-family:latine;" required>
</p>
<br>
<p style="font-family:latine;">Re-enter Password:
<input type="password" name="password-reenter" id="password-reenter" style="font-family:latine;" required>
</p>
<p>
<span id="password-success" style="color:green;"></span>
<span id="password-warning" style="color:red; "></span>
<input type="submit" name="btnSave" value="Try it">
</form>
&#13;
答案 1 :(得分:1)
var password = document.getElementById("password").value;
var password2 = document.getElementById("password-reenter").value;
在if
条件下,您没有检查password
和password2
,而是检查字符串。
应该是
if(password === password2){
并且onsubmit
是一个事件,您无法为其分配字符串。当您从表单的提交中调用checkpassword
时。仅阻止表单提交return false
。
var password = document.getElementById("password").value;
var password2 = document.getElementById("password-reenter").value;
function checkpassword(){
if(password === password2){
document.getElementById("password-warning").innerHTML = "";
}
else{
document.getElementById("password-warning").innerHTML = "The passwords do not match, please re-enter the password.";
return false;
}
};