'Detecting where a submit event came from with jQuery
I need to detect how a user submitted a form to generate some statistics. They can either press enter when typing on the input or they could click the submit button.
I tried binding a click event to the button and a keyup
event to the input but what happens is when I press enter the click event is triggered. I read in some other thread that this is part of the new HTML5 spec or something like that.
I then thought of binding a submit event to the form and detecting there what originated that event, but I've had no luck so far. Is that even possible?
EDIT
I guess I managed to fix it. I changed my keyup
event to keypress, like suggested by fortegente, and prevented the defaultEvents
from firing while at the same time triggering a submit event on the form. That seemed to do the trick.
Solution 1:[1]
You can try add custom attribute. Something like this:
$('form').submit(function(){
alert($(this).attr('event'));
});
$("button").on('click', function() {
$("form").prop("event", "click").submit();
});
$("input").on('keypress', function() {
if (e.which == 13) {
$("form").prop("event", "keypress").submit();
}
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | fortegente |