6

I want to manually invoke enter key press event on textbox through JS or jQuery.

I don't want to capture that event. I just want to invoke enter key press event.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Aditya K
  • 159
  • 1
  • 4
  • 13

3 Answers3

8

You can trigger it like:

// dummy event listener
$("input").keydown(function() { return true; });

var keyEvent = jQuery.Event("keydown");
keyEvent.keyCode = 13;
$("input").trigger(keyEvent);

See this post too: Definitive way to trigger keypress events with jQuery

Community
  • 1
  • 1
techfoobar
  • 65,616
  • 14
  • 114
  • 135
  • Not sure about that. I don't think it will! To counter this you can add a dummy 'listener' which does nothing and returns true. I've added a dummy listener in my answer. – techfoobar Dec 22 '11 at 18:59
  • 2
    LOL @ linking to the same post! Same thing this guy did: http://stackoverflow.com/a/8608515/398242 – Wesley Murch Dec 22 '11 at 19:00
  • Ahh! My mistake :) I've edited the post with the new link.. :) – techfoobar Dec 22 '11 at 19:03
  • This might just work. I believe jQuery will just add an additional event handler. So tacking this on at the end should still work even if there already is an event listener assigned. – hradac Dec 22 '11 at 20:18
  • This is really awesome.... Just had to change from "keyEvent.which" to "keyEvent.keyCode". keyCode works with IE. @techfoobar - I will mark this answer as accepted. But can you please put EDIT in your answer for "keyCode"? Thanks – Aditya K Feb 02 '12 at 11:32
  • `keyEvent.keyCode` don't work in my situation instead I use `keyEvent.which` that is work. source : http://stackoverflow.com/a/832121/1033510 – Mojtaba Kamyabi May 10 '17 at 06:19
0

Trigger the event with jQuery:

$(document).trigger('keypress');
Didier Ghys
  • 30,396
  • 9
  • 75
  • 81
0

You are looking for synthetic events. It's quite complicated. The following library takes care of it for you... http://jupiterjs.com/news/syn-a-standalone-synthetic-event-library

Here's example code using their lib

Syn.click( {},'hello' )
   .type( 'Hello World' )
   .delay()         //waits 600ms seconds by default
   .drag( $('#trash') , function() {
     ok( $('#hello').length == 0, "removed hello" )
   });
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217