I have a form with multiple buttons, each button can submit the form, I wanted to write some Jquery code to listen when the form was submitted through this button : (< type="button" data-identifier="buttons[_qf_PDF_upload]" class="ui-button ui-corner-all ui-widget">) so basically I wanted to combine two jquery listeners i.e .submit() and .click()
-
Does this answer your question? [Getting the ID of the element that fired an event](https://stackoverflow.com/questions/48239/getting-the-id-of-the-element-that-fired-an-event) – devlin carnate Oct 29 '20 at 21:49
-
actually my buttons dont have any id attribute on them, so I cant catch them with event.target.id – mali naeem Oct 29 '20 at 22:08
-
So, don't get the id attribute... that question and its answer show you how to find which element triggered the event. You can disregard the part about then obtaining the id of the element. (`event.target` is the element that triggered the event...do whatever you want with it) – devlin carnate Oct 29 '20 at 22:09
-
@devlincarnate actually I wanted to get the data-identifier attribute of the clicked button inside the submit() event – mali naeem Oct 29 '20 at 23:24
1 Answers
To get the button that was pressed to submit the form, you first need to attach an event listener to the form. As shown in the example below.
Then you need to prevent that form from being submitted using e.preventDefault()
From here we can access the event object which is passed as a parameter to the submit event callback. If you console.log(e)
you will see all the data that is available to you when submitting the form.
To access the button that submitted the form we look in originalEvent
submitter
- we can then access that specific button as a jQuery object by wrapping it in $()
.
In my example, I've changed the text of the button that submits the form.
<form id="my-form">
<button type="submit">Button 1</button>
<button type="submit">Button 2</button>
</form>
<script>
$('#my-form').submit(function(e){
e.preventDefault(); // Stop form sumbission while we handle the click event.
let clickedButton = $(e.originalEvent.submitter); // Get the button we just clicked in a jQuery object
// As an example, change the text of that button
clickedButton.html('You clicked me!');
});
</script>
From here you can run some functions depending on which button was pressed. For example, if you wanted to run a function when a button with the id
foo
was pressed you could add an if statement checking the buttons id, then run your function.

- 2,281
- 1
- 10
- 21
-
ok, can you tell me one more thing that how can I get value of attribute of that button, in my case 'data-identifier' attribute of that clicked button inside .submit() event ??? – mali naeem Oct 29 '20 at 23:18
-