Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 642
Chris Hynes Avatar asked Feb 12 '09 15:02

Chris Hynes


People also ask

What does Onsubmit in form do?

The onsubmit attribute provides the script datas to executed whenever the submit event is occurred so it does not submit the datas to the server with the help of submit() function it will be postponed to the server side.

Which of the following below event will be triggered when a form is submitted?

The onsubmit event occurs when a form is submitted.

What is the difference between Onclick and Onsubmit?

Onclick is the event where a control/object/pretty much anything, is clicked on. Onsubmit is the event where a form is submitted.

Can a form have an Onsubmit and action?

onsubmit is executed first in order to check the format etc. Then action is executed to get/post the data to the backend. If the form is valid and action is mentioned correctly then onsubmit never calls.


1 Answers

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.

like image 197
Joseph Tary Avatar answered Oct 29 '22 04:10

Joseph Tary