简体   繁体   中英

Detecting where a submit event came from with jQuery

So, 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.

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();
   }
});            

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM