确定哪些元素在onsubmit中提交了表单 [英] Determine which element submitted a form from within onsubmit

查看:108
本文介绍了确定哪些元素在onsubmit中提交了表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以确定哪个元素在onsubmit处理程序中提交了一个表单?试图编写一个知道哪个元素被点击的通用处理程序。例如,给定这种形式:

Is there a way to determine which element submitted a form from within an onsubmit handler? Trying to write a generic handler that knows which element was clicked. For example, given this form:

<form onsubmit="onSubmitHandler">
    <input type="submit" name="submit1" />
    <input type="submit" name="submit2" />
</form>

如何确定在onSubmitHandler里面点击了哪个提交按钮?我尝试了event.target / event.srcElement,但它给出了表单,而不是实际的提交按钮。

How can I determine inside the onSubmitHandler which submit button was clicked? I tried event.target/event.srcElement, but that gives the form, not the actual submit button.

更新:我正在写一个通用控件,所以它不知道形式上有什么。解决方案需要在不知道和更改表单的html的情况下工作。我的退后一步是走DOM查找可能会导致提交的所有按钮,但我想避免这种情况。

Update: I'm writing a generic control here, so it has no idea what's on the form. The solution needs to work without knowing and changing the html of the form. My fallback is walking the DOM to find all buttons that could cause a submit, but I'd like to avoid that.

推荐答案



An alternative solution would be to move the event trigger from the form's submit event, to the submit element's onclick event, as such:

<form name='form1'>  
    <input type="submit" name="submit1" onclick="onSubmitHandler"/>
    <input type="submit" name="submit2" onclick="onSubmitHandler"/>
</form>

在您的处理函数中,您可以通过检查事件目标的名称来确定提交元素,如果需要访问表单的信息或其他元素,你可以从提交元素的表单属性中获得。

In your handler function you can determine the submitting element simply by inspecting the event target's name, and if you need access to the form's information or other elements, you can get this from the submit elements "form" attribute.

这篇关于确定哪些元素在onsubmit中提交了表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆