我正在处理这个 HTML 表单,并且我正在尝试验证这些字段。我想使用 JavaScript 检查每个字段是否为空。如果该字段为空,我希望显示隐藏的关联 div。
当前问题:如果两个字段都留空,则只有第一个 div 会显示 proName 而不会显示第二个。我怎样才能让它们都出现?
<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>
谢谢!
最佳答案
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
}
关于javascript - 如何使用 JavaScript 验证此 HTML 表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14286044/