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

3

7

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?

Cirrose answered 2/4, 2013 at 20:42 Comment(2)
looks exactly like #3577969Selfgratification
#5722224 The answer to this is the top answer on the thread linked.Crumby
R
10
$('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;
});
Raster answered 2/4, 2013 at 20:43 Comment(3)
Using .submit() is a must, anyway to get the submitted button when using it?Cirrose
@AliBassam - Sure, just store the clicked button in data().Raster
This is far better than the alternatives I've seen, and this even defaults to the first button's name if the enter key is pressed. Although really, this should be using/submitting the button's value, not its name.Meshwork
E
7

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);
}();
Ephrayim answered 8/4, 2020 at 21:25 Comment(0)
D
6

Try this:

$(".myForm").submit(function(){
      var submitButton = $(":focus", this);
});
Dionisio answered 25/4, 2020 at 8:42 Comment(1)
Hi Marcos, thank you for your contribution. In order to give more support to your answer, I would suggest you to explain a little bit better the line of thought behind your proposed solutionTeratism

© 2022 - 2024 — McMap. All rights reserved.