form对象
form对象的属性:
name:表单的名称,主要用来让JS控制表单,
action:表单的数据处理程序
method:表单的提交方式,POST,GET
enctype:表单的编码方式
form对象的方法:
submit():提交表单,同:<input type = "submit" />
reset():重置变淡,与重置按钮功能一样
form对象的事件:
onsubmit:当单击提交按钮是发生,在数据发往服务器之前,主要用来在表单提交之前进行表单验证
onreset:当单击重置按钮时发生
获取表单元素
通过网页元素的id来获取对象,document.getElementById(id)
通过HTML标签名来获取对象,parentNode.getElemrntByTagName(tagName)
通过name属性来获取表单元素对象,表单中所有元素的起点都必须是document对象
document.formObj.elementObj
访问方式是三层结构,其中,formObj代表表单对象,elementObj代表表单元素对象
e.g.:document.form1.username.value.length
<title>Document</title>
<script type = "text/javascript">
window.onload = function(){
var thefrom = document.form1;
//alert(thefrom);
thefrom.method = "post";
thefrom.action = "login"
}
</script>
</head>
<body>
<form name = "form1">
username:<input type = "text" name = "username" />
passwd:<input type = "password" name = "userpwd">
<input type = "submit" value = "submit"/>
</form>
</body>
事件的返回值:
事件的返回值,会影响对象的默认动作。
如果事件返回false,则阻止默认动作的执行;
如果事件返回true或者空,则默认动作继续执行。
受事件返回值影响的事件有:onclick,onsubmit
表单提交和验证方法总结
使用submit按钮,结合onsubmit事件来实现
-
function checkForm(){ //判断用户名是否为空 if (document.form1.username.value=="") { window.alert("no null!") return false; }else{ window.alert("ok") return true; } } </script> </head> <body> <form name = "form1" onsubmit = "return checkForm()"> username:<input type = "text" name = "username" /> passwd:<input type = "password" name = "userpwd"> <input type = "submit" value = "submit"/>
-
使用submit 按钮,结合onclick事件实现表单的验证和提交
-
<input type = "submit" value = "submit" onclick="return checkForm()" />
-
button按钮(普通按钮),结合submit()方法实现表单的验证提交
-
<script type = "text/javascript"> function checkForm(){ if (document.form1.username.value.length ==0){ window.alert("not null") }else if(document.form1.username.value.length < 5 || document.form1.username.valuellength > 20){ window.alert("should 5<value<20") }else if(checkOtherchar(document.form1.username.value)){ window.alert("not specific symbol!") }else{ window.alert("submit ok"); //表单提交 document.form1.submit(); } } function checkOtherchar(str) { //定义一个特殊符号的数组 var arr = ["*","&","<",">","$"] for (var i = 0; i < arr.length ; i++) { for(var j = 0;j < str.length ;j++ ) { if (arr[i] == str.charAt(j)) { return true; } } } return false; } </script> </head> <body> <form name = "form1" action = "login.php"> username:<input type = "text" name = "username" /> passwd:<input type = "password" name = "userpwd"> <input type = "button" value = "submit" onclick = "checkForm()" /> </form> </body>
-