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.
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)
{
....
}
});
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With