我正在处理一个html表单,我必须输入用户信息并提交。它将导航到php连接页面。问题是我在通过JavaScript提交之前一直在尝试验证数据并且它没有发生。
下面我发布了HTML表单代码。
<!DOCTYPE html>
<html>
<head>
<script language = "JavaScript">
function validate()
{
var username = document.getElementById("userName").value;
var password = document.getElementById("Password").value;
var repassword = document.getElementById("RePassword").value;
if (username.length < 0) {
alert("Please enter the username.");
return false;
}
if (password == null || password == "") {
alert("Please enter the password.");
return false;
}
if (repassword == null || repassword == "" || repassword != password) {
alert("Please enter the password.");
return false;
}
}
</script>
</head>
<body>
<form name="frmMr" action="send_post.php" method="post" onsubmit="return(validate());">
User Name:<br> <input type="text" name="userName"><br>
Enter Password:<br> <input type="text" name="Password"><br>
Reenter Password:<br> <input type="text" name="RePassword"><br>
<input type="submit" >
</form>
<p id="error_para" ></p>
</body>
</html>
答案 0 :(得分:3)
您的HTML没有id
标记,而在Javascript中您使用的是getElementById('')
<!DOCTYPE html>
<html>
<head>
// Changed the script syntax
<script type="text/javascript">
function validate() {
var username = document.getElementById("userName").value;
var password = document.getElementById("Password").value;
var repassword = document.getElementById("RePassword").value;
if (username.length <= 0) {
alert("Please enter the username.");
return false;
}
if (password == null || password == "") {
alert("Please enter the password.");
return false;
}
if (repassword == null || repassword == "" || repassword != password) {
// Changed Password message for testing
alert("Confirm Password empty or do not match.");
return false;
}
}
</script>
</head>
<body>
<form name="frmMr" action="send_post.php" method="post" onsubmit="return(validate());">
User Name:<br> <input type="text" id="userName" name="userName"><br>
Enter Password:<br> <input type="text" id="Password" name="Password"><br>
Reenter Password:<br> <input type="text" id="RePassword" name="RePassword"><br>
<!-- Added id="" attribute to above 3 lines -->
<input type="submit" >
</form>
<p id="error_para" ></p>
</body>
</html>
答案 1 :(得分:2)
您忘记将IDS添加到所有字段
<input type="text" name="userName" id="userName">
等......
答案 2 :(得分:1)
我还建议在HTML5中使用required
属性作为输入。
<input type="text" id="userName" name="userName" required>
它标记了所需的字段(如名称所示),如果表单中没有值,表单将不会提交。
答案 3 :(得分:-2)
最后,return true;
在你的功能结束时