Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery detect which button submitted form

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.

like image 439
Ian Wood Avatar asked Jan 31 '13 14:01

Ian Wood


2 Answers

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)
    {
        ....
    }
});
like image 87
musefan Avatar answered Sep 28 '22 10:09

musefan


This answer is an improvement of @musefan's answer.

Avoid global variables. It is better to keep data in form:

$('button[type=submit]').click(function (e) {
    var button = $(this);
    buttonForm = button.closest('form');
    buttonForm.data('submittedBy', button);
});

And in submit handler just get it:

$('#my-form').submit(function (e) {
    var form = $(this);
    var submittedBy = form.data('submittedBy');
    if(submittedBy.val() == 1) {
        // Any code here...
    }
});

Form could be submitted by hitting 'enter'. To avoid null in submittedBy variable:

var submittedBy = form.data('submittedBy') || form.find('button[type=submit]:first');
like image 30
Jekis Avatar answered Sep 28 '22 08:09

Jekis