Javascript 表单校验的三种方法

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <style type="text/css">
        #main{width:300px;margin:0px auto;background-color:Red;}
    </style>
    <script type="text/javascript">
        function checkName1() {
            var name = document.getElementById("txtName").value;
            if (name == "") {
                alert("姓名不能为空!");
                return false;
            }
            else {
                return true;
            }
        }
        function checkName2() {
            var name = document.getElementById("txtName").value;
            if (name == "") {
                alert("姓名不能为空!");
                return false;
            }
            else {
                document.getElementById("mf").submit();//使用form的submit方法
            }           
        }
    </script>
</head>
<body>
    <form id="mf" action="动态切换小图大图.htm" method="get">
    <!--方法3<form id="mf" onsubmit="return checkName1();" action="动态切换小图大图.htm" method="get">-->
        <div id="main">
            姓名:<input type="text" id="txtName" />
            <input type="submit" value="点我提交(我是提交按钮)1" onclick="return checkName1();" />    <!--方法1-->
            <input type="button" value="点我提交2" onclick="checkName2();" />   <!--方法2-->
        </div>
    </form>
</body>
</html>

你可能感兴趣的:(Javascript 表单校验的三种方法)