如何使用JavaScript验证此HTML表单?
16lz
2021-01-22
I'm working with this HTML form, and I am attempting to validate the fields. I would like to check that each field is not empty using JavaScript. If the field is empty, I want the hidden associated div to be displayed.
我正在使用这个HTML表单,我正在尝试验证字段。我想使用JavaScript检查每个字段是否为空。如果该字段为空,我希望显示隐藏的关联div。
CURRENT PROBLEM: If both fields are left empty, only the first div is shown for proName and the second is not revealed. How can I make them both appear?
当前问题:如果两个字段都留空,则只显示proName的第一个div,而不显示第二个div。我怎样才能让它们出现?
<html>
<body>
<form action="" method="post" class="form" name="form" onsubmit="return validateForm();">
<p><label for="proName">Processors Name: </label>
<input type="text" name="proName" id="proName"></p>
<div id="alertProName" style="display:none;">
<p>Please fill in this field</p>
</div>
<p><label for="compName">Company Ordered Through: </label>
<input type="text" name="compName" id="compName"></p>
<div id="alertCompName" style="display:none;">
<p>Please fill in this field</p>
</div>
</form>
<script type="text/javascript">
function validateForm() {
var x=document.forms["form"]["proName"].value;
if (x==null || x=="") {
var s = document.getElementById("alertProName").style.display="block";
return false;
}
};
function validateForm() {
var z=document.forms["form"]["compName"].value;
if (z==null || z=="") {
var a = document.getElementById("alertCompName").style.display="block";
return false;
}
};
</script>
</body>
</html>
Thank you!
谢谢!
5 个解决方案
#1
3
function validateForm(){
var valid = true;
var x=document.forms["form"]["proName"].value;
if (x==null || x=="") {
document.getElementById("alertProName").style.display="block"; //show the error message
valid = false;
}else{
document.getElementById("alertProName").style.display="none"; // hide the error message
}
var z=document.forms["form"]["compName"].value;
if (z==null || z=="") {
document.getElementById("alertCompName").style.display="block";//show the error message
valid = false;
}else{
document.getElementById("alertCompName").style.display="none"// hide the error message
}
return valid; // only if both are valid will we submit
}
更多相关文章
- html5: 新特性(表单)
- 我无法在某些Web浏览器中输入我的注册文本字段
- Jquery - 表单验证,为错误消息添加css样式
- 将文本从表单复制到另一个网站的文本字段
- J2EE进阶之onsubmit表单提交 五
- jquery入门-$.each 数组操作与表单操作代码
- 的良好实践是什么?它可以替换还是只用于表单?
- 【ASP.NET Web API教程】5.2 发送HTML表单数据:URL编码的表单数据
- 我正在尝试使用带有post方法的AJAX将用户名和密码发送到php文件