第一种方式:表单提交,在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> |
第二种方式:通过button按钮来触发表单提交事件,会忽略掉其他标签中的属性,比如form标签中的onsubmit属性就失效了。这时为了进行表单验证,可以将验证代码放在submitForm();方法中进行验证。
?
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按钮来触发表单提交事件,会忽略掉其他标签中的属性,比如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提交表单的几种方法和验证(必看篇)
原文地址:http://www.cnblogs.com/tengqiuyu/p/7611765.html