js验证表单
注意:
- 只做非空验证, 只是个小demo
- 学习思想,onblur onfocus onsubmit的使用,给出友好提示
- 网上有很多有良好,强大的控件,用于用户输入
代码实现
- js代码
<script>function check_form(form) {// 得到form表单的所有input标签var els = form.getElementsByTagName("input");for(var i = 0; i < els.length; i ++) {// alert(typeof(els[i].getAttribute("onblur")));// 有onblur失焦事件的input框if (typeof(els[i].getAttribute("onblur")) == "function" || typeof(els[i].getAttribute("onblur")) == "string") {if (!check_item(els[i])) {return false;}}}return true;}function check_item(obj) {// input标签的值var value = obj.value.trim();// 根据层级关系取到label标签var msgBox = obj.parentNode.getElementsByTagName("label")[0];// 选择标签名,如果是空,给出提示switch (obj.name){ case "name": if (value == "") {msgBox.className = "change_color";msgBox.innerText = "填写姓名";return false;}case "age":if (value == "") {msgBox.className = "change_color";msgBox.innerText = "填写年龄"; return false;}/*case "gender": break;*/case "birthday":if (value == "") {msgBox.className = "change_color";msgBox.innerText = "填写生日"; return false; }}return true;}function check_focus(obj) {var msgBox = obj.parentNode.getElementsByTagName("label")[0];// 当鼠标在文本框上,清空消息框msgBox.className = "change_color";msgBox.innerText = "";}</script>
- 页面
<!DOCTYPE html>
<html><head><meta charset="utf-8" /><title></title><style>table {width: 500px;text-align: center;}td {border-style: none;}.change_color {color: red;}</style><!-- 类选择器, 不符合条件, 改变label的颜色 --> <script>// 在上面</script></head><body><form action="post" onsubmit="return check_form(this)"><table align="center" border="1px" cellpadding="0" cellspacing="0"><tr><td>姓名</td><td><input type="text" name="name" onblur="check_item(this)" onfocus="check_focus(this)" /><label class="change_color"></label></td></tr><tr><td>年龄</td><td><input type="text" name="age" onblur="check_item(this)" onfocus="check_focus(this)" /><label class="change_color"></label></td></tr><tr><td>性别</td><td><input type="radio" name="gender" value="男" checked="checked"/>男<input type="radio" name="gender" value="女"/>女</td></tr><tr><td>生日</td><td><input type="text" name="birthday" onblur="check_item(this)" onfocus="check_focus(this)"/><label class="change_color"></label> </td></tr> <tr><td colspan="2"><input type="submit" value="提交"/><input type="reset" value="重置" /></td></tr> </table></form></body>
</html>
- 测试
- 当我输入不填内容时,onblur,给出提示
-
填年龄时,onfocus 清除后面的提示
-
填写完整
-
提交check_form判断,地址栏显示提交数据