form對象
form對象
一個(gè)<form>標(biāo)記,就是一個(gè)<form>對象。
form對象的屬性
name:表單的名稱,主要用來讓JS來控制表單。
action:表單的數(shù)據(jù)處理程序(PHP文件)。
method:表單的提交方式,取值:GET、POST
enctype:表單數(shù)據(jù)的編碼方式。
form對象的方法
submit():提交表單,與<input ?type = “submit”?/>功能一樣。
reset():重置表單,與重置按鈕功能一樣。
form對象的事件
onsubmit:當(dāng)單擊提交按鈕時(shí)發(fā)生,并數(shù)據(jù)發(fā)往服務(wù)器之前發(fā)生。主要用來“在表單提交之前進(jìn)行表單驗(yàn)證”。
onreset:當(dāng)單擊重置按鈕時(shí)發(fā)生。
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>php.cn</title> <script type="text/javascript"> window.onload = function(){ //獲取form對象 var formObj = document.form1; //增加method屬性 formObj.method = "post"; //增加action屬性 formObj.action = "login.php"; } </script> </head> <body> <form name="form1"> 用戶名:<input type="text" name="username" /> 密碼:<input type="password" name="userpwd" /> <input type="submit" value="提交表單" /> </form> </body> </html>
獲取表單元素
通過網(wǎng)頁元素的id來獲取對象。document.getElementById(id)
通過HTML標(biāo)簽名來獲取對象。parentNode.getElementsByTagName(tagName)
通過name屬性來獲取表單元素對象。表單中所有元素的起點(diǎn)都必須是document對象。
語法:document.formObj.elementObj
訪問方式是三層結(jié)構(gòu)。其中,formObj代表表單對象,elementObj代表表單元素對象。
舉例:document.form1.username.value.length
事件返回值
事件的返回值,會(huì)影響對象的默認(rèn)動(dòng)作。如:<a>標(biāo)記的默認(rèn)動(dòng)作是打開一個(gè)網(wǎng)址。
如果事件返回false,則阻止默認(rèn)動(dòng)作的執(zhí)行;如果事件返回true或空,則默認(rèn)動(dòng)作繼續(xù)執(zhí)行。
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>php.cn</title> </head> <body> <a href="http://miracleart.cn" onclick="return false">PHP中文網(wǎng)</a> </body> </html>
受返回值影響的事件有兩個(gè):onclick、onsubmit。