I have a .submit()
event set up for form submission. I also have multiple forms on the page, but just one here for this example. I\'d like to know which submi
I have found the best solution is
$(document.activeElement).attr('id')
This not only works on inputs, but it also works on button tags. Also it gets the id of the button.
You can create input type="hidden" as holder for a button id information.
<input type="hidden" name="button" id="button">
<input type="submit" onClick="document.form_name.button.value = 1;" value="Do something" name="do_something">
In this case form passes value "1" (id of your button) on submit. This works if onClick occurs before submit (?), what I am not sure if it is always true.
Here is my solution:
$('#form').submit(function(e){
console.log($('#'+e.originalEvent.submitter.id));
e.preventDefault();
});
I found that this worked.
$(document).ready(function() {
$( "form" ).submit(function () {
// Get the submit button element
var btn = $(this).find("input[type=submit]:focus" );
});
}
I write this function that helps me
var PupulateFormData= function (elem) {
var arr = {};
$(elem).find("input[name],select[name],button[name]:focus,input[type='submit']:focus").each(function () {
arr[$(this).attr("name")] = $(this).val();
});
return arr;
};
and then Use
var data= PupulateFormData($("form"));
When the form is submitted:
document.activeElement
will give you the submit button that was clicked.
document.activeElement.getAttribute('value')
will give you that button's value.
Note that if the form is submitted by hitting the Enter key, then document.activeElement
will be whichever form input
that was focused at the time. If this wasn't a submit button then in this case it may be that there is no "button that was clicked."