2 回答
TA贡献1811条经验 获得超6个赞
看起来罪魁祸首是您试图访问Firstname该document对象。
我用更标准的document.getElementById()方法和它的工作替换了它。
一些阅读:Do DOM tree elements with ids become global variables?
function validate() {
var invalid = false;
if(!document.getElementById('Firstname').value.length) {
invalid = true;
}
if(invalid) {
document.getElementById("form-error").style.display = "inline-block";
return false;
}
return true;
}
#form-error {
display: none;
}
<form id="NewPatientForm" method="post" action="#" onsubmit="return validate()">
<div class="form-element">
<p id="form-error">All fields are required</p>
</div>
<div>
<label for="Firstname">First Name
<input type="text" name="Firstname" placeholder="First Name" id="Firstname">
</label>
</div>
<div>
<input type="submit" name="submit-button" value="Submit">
</div>
</form>
TA贡献1853条经验 获得超6个赞
有几个错别字,我也会提出其他建议。首先,代码中的一个或三个修复:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>NewPatientForm</title>
<script>
function validate() {
const invalid = document.getElementById("Firstname").value.length == 0;
if(invalid) {
document.getElementById("form-error").style.display = "inline-block";
return false; //to make the text appear
}
return true;
}
</script>
</head>
<body>
<form id="NewPatientForm" method="post" action="#" onsubmit="return validate();">
<div class="form-element">
<p id="form-error">All fields are required</p>
</div>
<div>
<label for="Firstname">First Name
<input type="text" name="Firstname" placeholder="First Name" id="Firstname">
</label>
</div>
<div>
<input type="submit" name="submit-button" value="Submit">
</div>
</form>
</body>
</html>
我的建议是您还可以查看内置的 HTML 表单验证属性。我认为您正在重新发明轮子,例如要求非空名字。为什么不用这个而不是 JavaScript?
<input type="text" name="Firstname" id="Firstname" placeholder="First Name" required />
还有很多其他的,比如 minlength=""、min=""、step="" 等。
此外,还有一个带有 .checkValidity() 的验证系统中的 JavaScript 挂钩,因此您可以让内置验证完成繁重的工作,然后也加入更多您自己的自定义方面。
添加回答
举报
