27
2017
09

表单验证

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style> p{ text-indent: 30px; } input{ outline: none; } .isNull{ border: 1px solid red; } </style>

        <script> var names = ["tom","jack","lily"]; function mySub(){ var k = 0; var name = document.forms['myForm']['name']; var pwd = document.forms['myForm']['pwd']; var hobbys = document.forms['myForm']['hobby']; var xl = document.forms['myForm']['xl']; if(name.value.trim() == ""){ name.className = "isNull"; } if(pwd.value.trim() == ""){ pwd.className = "isNull"; } for(var i = 0 ; i < hobbys.length ; i++){ if(hobbys[i].checked == true){ k++; } } if(k<1){ document.getElementById("isHobby").className = "isNull"; } if(xl.value == "请选择"){ xl.className = "isNull"; } return false; } //还原表单元素样式 function inputFocus(obj){ obj.className = ""; } //判断用户名是否重复 function isName(obj){ var b = true; for (var i=0 ; i<names.length ; i++) { var n = names[i]; if(n == obj.value){ document.getElementById("isCan").innerHTML = "用户名以被注册!"; obj.className = "isNull"; b = false; break; } } if(b){ //当用户名不重复时 document.getElementById("isCan").innerHTML = ""; } } //下拉框内容改变事件 function myChange(obj){ if(obj.value != "请选择"){ obj.className = ""; } } //复选框事件 function mySelect(){ document.getElementById("isHobby").className = ""; } </script>

    </head>
    <body>

        <h1>用户注册</h1>
        <hr />

        <form name="myForm" action="a.html" method="get" onsubmit="return mySub()">

            <p>
                用户名:<input name="name" type="text" onfocus="inputFocus(this)" onblur="isName(this)" />
                <span id="isCan" style="font-size: 14px;color: red;"></span>
            </p>
            <p>
                密码:<input name="pwd" type="password" onfocus="inputFocus(this)" />
            </p>
            <p>
                性别:
                <input type="radio" name="sex" value="男" checked /><input type="radio" name="sex" value="女" /></p>
            <p id="isHobby">
                爱好:
                <input type="checkbox" name="hobby" value="篮球" onclick="mySelect()" />篮球
                <input type="checkbox" name="hobby" value="足球" onclick="mySelect()" />足球
                <input type="checkbox" name="hobby" value="乒乓球" onclick="mySelect()" />乒乓球
                <input type="checkbox" name="hobby" value="羽毛球" onclick="mySelect()" />羽毛球
            </p>
            <p>
                学历:
                <select name="xl" onchange="myChange(this)">
                    <option>请选择</option>
                    <option>中学</option>
                    <option>大专</option>
                    <option>本科</option>
                    <option>研究生</option>
                </select>
            </p>
            <p>
                <input type="submit" />
            </p>

        </form>

    </body>
</html>
上一篇:Photon_PhotonServer安装_009 下一篇:响应式布局的两个例子