Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get clicked submit button when submitting a form via JQuery

I have a form with 2 submit buttons.

<form class="myForm">
     <!-- Some Inputs Here -->
     <input type="submit" name="firstSubmit" value="first submit" />
     <input type="submit" name="secondSubmit" value="second submit" />
</form>

I am submitting this form via JQuery.

$(".myForm").submit(function(){
      var submitButton = ? //I need to catch the submit button that was clicked
});

How can I know which submit button was clicked?

like image 932
Ali Bassam Avatar asked Apr 02 '13 20:04

Ali Bassam


People also ask

How do you submit a form when a button is clicked?

In javascript onclick event , you can use form. submit() method to submit form. You can perform submit action by, submit button, by clicking on hyperlink, button and image tag etc. You can also perform javascript form submission by form attributes like id, name, class, tag name as well.

Can a submit button have an onclick?

In both the cases, pressing the button will submit the parent form without the need for handling the onclick event separately. If you want to validate the form before submitting, the best event handler would be the onsubmit event of the form.


2 Answers

$('input[type="submit"]').on('click', function(){
      $('.myForm').data('button', this.name);
});

$(".myForm").on('submit', function(){
  var submitButton = $(this).data('button') || $('input[type="submit"]').get(0).name;
});
like image 150
adeneo Avatar answered Oct 30 '22 11:10

adeneo


There is now a standard submitter property in the submit event.
Already implemented in firefox!

document.addEventListener('submit',function(e){
    console.log(e.submitter)
})

in jQuery you just write

$(".myForm").on('submit', function(e){
  e.originalEvent.submitter
});

for browsers not supporting it use this polyfill:

!function(){
    var lastBtn = null
    document.addEventListener('click',function(e){
        if (!e.target.closest) return;
        lastBtn = e.target.closest('button, input[type=submit]');
    }, true);
    document.addEventListener('submit',function(e){
        if (e.submitter) return;
        var canditates = [document.activeElement, lastBtn];
        for (var i=0; i < canditates.length; i++) {
            var candidate = canditates[i];
            if (!candidate) continue;
            if (!candidate.form) continue;
            if (!candidate.matches('button, input[type=button], input[type=image]')) continue;
            e.submitter = candidate;
            return;
        }
        e.submitter = e.target.querySelector('button, input[type=button], input[type=image]')
    }, true);
}();
like image 31
Tobias Buschor Avatar answered Oct 30 '22 10:10

Tobias Buschor