Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

javascript - Determine which element submitted a form from within 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>

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...