jquery detect which button submitted form

Ian Wood picture Ian Wood · Jan 31, 2013 · Viewed 12.4k times · Source

I have a form with the following:

<form id="my-form" ...>
    ...
    <button type="submit" name="bttnsubmit" value="1">The first button</button>
    <button type="submit" name="bttnsubmit" value="2">The last button</button>
</form>

I'd like to detect which triggered the form submit event using just:

$('#my-form').submit(function(){
    //psuedo code
    if($('[name=bttnsubmit]').val() == 1) {
        ....
    }
});

Obviously that selector will always return the value of the first bttnsubmit element it comes across, so I need some other magic selector or filter or something.

I have seen $('[name=bttnsubmit][clicked=true]') touted about but that has not yet worked in my attempts...

I could of course resort to $('[name=bttnsubmit]').click() but would prefer to be able to achieve my goals in the forms submit event.

Any help/tips much appreciated.

Answer

musefan picture musefan · Jan 31, 2013

I don't know if there is any built in event data (maybe there is) but one idea that comes to mind is to handle the click event of the buttons and store a global reference of the value. Something like this:

var ButtonValue;

$('button[type="submit"]').click(function(e){
   ButtonValue = $(this).val();
});

$('#my-form').submit(function(){
    //psuedo code
    if(ButtonValue == 1)
    {
        ....
    }
});