---
title: "关于 OnSubmit"
author: "ware"
date: "2010-12-11T11:53:00Z"
tags: []
categories: ["Web前端"]
slug: "onsubmit"
draft: false
lastmod: "2010-12-11T11:53:00Z"
id: 839489
url: "https://ware.iteye.com/blog/839489"
---

onsubmit的执行函数必须是一个具有true或false返回值的函数,否则,验证也会被忽略
所以onsubmit的写法通常是onsubmit="return(function())",而不是onsubmit="function()"

http://letle.iteye.com/blog/82237  :

submit()和onsubmit()的区别 

最近在开发中遇到了表单提交前验证的问题，用一个普通的button按钮代替submit按钮， 
在提交前触发这个button的onclick事件，在其事件中触发form的submit事件。问题出现了： 
以下是出现相关代码：


<form action="http://www.baidu.com/s?wd=this.form.submit%28%29%3B&cl=3" method="post" name="form1" onsubmit="return alert('已提交！'); return false;">   
    <table align="center" width="420px" cellPadding="2" cellSpacing="1" bgcolor="#A4B6D7"    style="word-wrap:Break-word;">                  
        <tr style="cursor: hand;background:#d7e3f6" >   
            <td width="20%" align="right">条型码</td>   
            <td><input style="width:90%" type="text" name="GOODSNUM"   size="30"  maxlength="8" ></td>   
        </tr>   
        <tr>   
            <td align="center" colspan="2">   
                <input type="button" name="save" value="保存" onclick="if((confirm('确定要提交吗？'))) this.form.submit();"/>   
            </td>   
        </tr>    
    </table>   
</form>  
<form action="http://www.baidu.com/s?wd=this.form.submit%28%29%3B&cl=3" method="post" name="form1" onsubmit="return alert('已提交！'); return false;">
 <table align="center" width="420px" cellPadding="2" cellSpacing="1" bgcolor="#A4B6D7" style="word-wrap:Break-word;">    
  <tr style="cursor: hand;background:#d7e3f6" >
   <td width="20%" align="right">条型码</td>
   <td><input style="width:90%" type="text" name="GOODSNUM"   size="30"  maxlength="8" ></td>
  </tr>
  <tr>
   <td align="center" colspan="2">
    <input type="button" name="save" value="保存" onclick="if((confirm('确定要提交吗？'))) this.form.submit();"/>
   </td>
  </tr> 
 </table>
</form>
却发现并没有触发form的onsubmit方法，而是直接提交了。奇怪了，难道没有这种方式无法结合form的onsubmit方法吗？ 
仔细想了想，既然this.form表示form这个对象，那么肯定能获取到form的属性和方法的 
，就改成this.form.onsubmit(); 成功！ 
我又查了查手册，原来submit的方法是这样解释的： 
The submit method does not invoke the onsubmit event handler. Call the onsubmit event handler directly. When using Microsoft® Internet Explorer 5.5 and later, you can call the fireEvent method with a value of onsubmit in the sEvent parameter. 

意思是说submit这个方法是不触发onsubmit时间的，如果想要触发它，需要调用 
fireEvent方法。尝试一下：this.form.fireEvent('onsubmit');哈哈，果然也成功！不过这样不是多此一举吗？呵呵！ 

就这个小问题也搞了我将近一个小时，不过为了以后不为这个问题烦恼，这也是值得的。 
this.form.submit(); //直接提交表单 
this.form.onsubmit(); //调用form的onsubmit方法 
this.form.fireEvent('onsubmit'); //同上, 
PS:又学到了fireEvent这个方法