所需属性在此表单中不起作用。如何解决这个问题?
<form id="regform" action="PersonalDataAgreement.jsp" method="post" name="registration_form">
<div class="register">
<div class="input_field">
<input type="text" placeholder="familyname" class="input" name="familyname" id="familyname" required>
</div>
<div class="input_field">
<input type="text" placeholder="firstname" class="input" name="firstname" id="firstname" required>
</div>
<div class="input_field">
<input type="text" placeholder="secondname" class="input" name="secondname" id="secondname" required>
</div>
<div class="btn"><a href="#" onclick="document.getElementById('regform').submit()">Register</a></div>
</div>
</form>
调用表单的submit()
方法将绕过验证步骤。
使用一个真正的提交按钮。应用CSS使它看起来像你想要的那样。
<button>Register</button>
从JS代码提交表单会忽略必需的属性。您还可以在提交表单之前通过JS代码验证输入字段。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form id="regform" action="PersonalDataAgreement.jsp" method="post" name="registration_form">
<div class="register">
<div class="input_field">
<input type="text" placeholder="familyname" class="input" name="familyname" id="familyname" required>
</div>
<div class="input_field">
<input type="text" placeholder="firstname" class="input" name="firstname" id="firstname" required>
</div>
<div class="input_field">
<input type="text" placeholder="secondname" class="input" name="secondname" id="secondname" required>
</div>
<div class="btn"><a href="#" onclick="handleSubmit(event)">Register</a></div>
</div>
</form>
<script>
function handleSubmit(e){
e.preventDefault();
familyName = document.getElementById('familyname');
firstName = document.getElementById('firstname');
secondName = document.getElementById('secondname');
if (familyName.value === "" || firstName.value === "" || secondName.value === "") {
alert("Please fill the required fields")
//here you can validate inputs
}else{
document.getElementById('regform').submit()
}
}
</script>
</body>
</html>
更改您的"注册";按钮:
<div class="btn"><button>Register</button></div>
效果很好。