利用JS提交表單的幾種方法和驗證(必看篇)
阿新 • • 發佈:2017-09-29
www contain 功能 ner ble 四種 利用 comm pac
通過button按鈕來觸發表單提交事件onclick="submitForm();",會忽略掉其他標簽中的屬性,比如form標簽中的onsubmit屬性就失效了。這時為了進行表單驗證,可以將驗證代碼放在submitForm();方法中進行驗證。
?
第一種方式:表單提交,在form標簽中增加onsubmit事件來判斷表單提交是否成功
?1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<script type= "text/javascript" >
function validate(obj) {
if (confirm( "提交表單?" )) {
alert(obj.value);
return true ;
} else {
alert(obj.value);
return false ;
} }
</script>
<body>
<form action= "http://www.jb51.net" onsubmit= "return validate(document.getElementByIdx_x(‘myText‘));" > <!—參數的這種寫法註意下-->
<input type= "text" id= "myText" />
<input type= "submit" value= "submit" />
</form>
</body>
|
第二種方式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<script type= "text/javascript" >
function validate() {
if (confirm( "提交表單?" )) {
return true ;
} else {
return false ;
}
}
function submitForm() {
if (validate()) {
document.getElementByIdx_x( "myForm" ).submit();
}
}
</script>
<body>
<form action= "http://www.jb51.net" id= "myForm" >
<input type= "text" />
<input type= "button" value= "submitBtn" onclick= "submitForm();" /> <!—也可以使用document.getElementByIdx_x(“該按鈕的id”).click();來執行onclick事件-->
</form>
</body>
|
第三種方式:將onsubmit事件放在submit標簽中,而不是form標簽中,此時表單驗證失效,點擊提交按鈕表單直接提交
?1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<script type= "text/javascript" >
function validate() {
if (confirm( "提交表單?" )) {
return true ;
} else {
return false ;
}
}
</script>
<body>
<form action= "http://www.jb51.net" >
<input type= "text" />
<input type= "submit" value= "submit" onsubmit= "return validate()" />
</form>
</body>
|
第四種方式:為submit按鈕添加上onclick事件,其中該事件用於表單提交的驗證,功能類似於在form標簽中增加了onsubmit事件一樣
?1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<script type= "text/javascript" >
function validate() {
if (confirm( "提交表單?" )) {
return true ;
} else {
return false ;
}
}
</script>
<body>
<form action= "http://www.jb51.net" >
<input type= "text" />
<input type= "submit" value= "submit" onclick= "return validate()" />
</form>
</body>
|
第五種方式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<body>
<form action= "http://www.jb51.net" id= "myForm" >
<input type= "text" />
<input type= "button" value= "submitBtn" id= "myBtn" />
</form>
</body>
<script type= "text/javascript" >
function validate() {
if (confirm( "提交表單?" )) {
return true ;
} else {
return false ;
}
}
|
通過button按鈕來觸發表單提交事件onclick="submitForm();",會忽略掉其他標簽中的屬性,比如form標簽中的onsubmit屬性就失效了。這時為了進行表單驗證,可以將驗證代碼放在submitForm();方法中進行驗證
?1 2 3 4 5 6 7 8 |
function submitForm() {
if (validate()) {
document.getElementByIdx_x( "myForm" ).submit();
}
}
document.getElementByIdx_x( "myBtn" ).onclick = submitForm;
</script>
|
以上這篇利用JS提交表單的幾種方法和驗證(必看篇)就是小編分享給大家的全部內容了,希望能給大家一個參考
利用JS提交表單的幾種方法和驗證(必看篇)