from表单提交之前数据判空

在input标签中写onclick事件,不管返回是真是假都会继续提交表单。

使用onsubmit事件

   <form action="login.html" method='post' onsubmit="return check();">
          姓名:<input type='text' name='name' id='name' size='12' maxlenght='6' value=''></input>
          <br/>
          密码:<input type='password' name='password' id='password' size='12' maxlength='10' value=''></input>
          <br/><input type='radio' name='sex' value='男' checked></input><input type=radio name='sex' value='女'></input>
          <br/>
    <input type='submit' value='登陆'></input>
    <input type='reset' value='重置' ></input>
    </form>
    <script type="text/javascript">
        function check() {
            var name = document.getElementById("name").value;
            if(name == '') {
                alert("姓名不能为空!");
                return false;
            }
            var password = document.getElementById("password").value;
            if(password == '') {
                alert("密码不能为空!");
                return false;
            } else if (password.length() < 6 || password.length() > 10) {
                alert("密码长度在6到10位之间!");
                return false;
            }
            /* var sex = document.getElementsByName("sex");
            if(!sex[0].checked && !sex[1].checked) {
                alert("性别项不能为空!");
                return false;
            } */
            return true;
        }
    </script>

 

posted @ 2018-10-23 20:11  xianting  阅读(1340)  评论(0编辑  收藏  举报