js判断所有表单值是否为空

<!DOCTYPE html>
<html>
  <head>
    <title>提交表单页</title>
    <meta charset="UTF-8"/>
    <script type="text/javascript">
      function myCheck()
      {//遍历所有表单元素
        for(var i=0;i<document.form1.elements.length-1;i++)
        {//判断所有表单值是否为空
         if(document.form1.elements[i].value=="")
         {
           alert("当前表单不能有空项");
           //将光标定位在空表单处
           document.form1.elements[i].focus();
           return false;
         }
        }
        return true;
        
      }
    </script>
  </head>
  <body>
     <form name="form1" method="post" action="page2.html" onSubmit="return myCheck()">
       用户名:<input type="text" name="username"><br>
       性别:<input type="text" name="sex"><br>
       出生时间:<input type="text" name="birthday"><br>
       <input type="submit" value="提交">
     </form>
  </body>
</html>

猜你喜欢

转载自blog.csdn.net/thinkpet/article/details/80155656