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
}

更多相关文章

  1. html5: 新特性(表单)
  2. 我无法在某些Web浏览器中输入我的注册文本字段
  3. Jquery - 表单验证,为错误消息添加css样式
  4. 将文本从表单复制到另一个网站的文本字段
  5. J2EE进阶之onsubmit表单提交 五
  6. jquery入门-$.each 数组操作与表单操作代码
  7. 的良好实践是什么?它可以替换还是只用于表单?
  8. 【ASP.NET Web API教程】5.2 发送HTML表单数据:URL编码的表单数据
  9. 我正在尝试使用带有post方法的AJAX将用户名和密码发送到php文件

随机推荐

  1. C语言中for用法是什么?
  2. 在c语言中二维数组元素在内存中的存放顺
  3. C程序总是以main函数作为程序执行的起始
  4. c语言数组冒泡排序是如何实现的?
  5. c语言怎么实现三个数从小到大输出?
  6. 在C语言里二维数组在内存中的存放顺序是
  7. c语言n次方怎么输入?
  8. c语言三目运算符怎么用?
  9. C++与C语言的区别与联系
  10. C++语言标识符的命名规则是什么?