37

I need to know how to trigger an enter key on an input. That is, in response to some other event (not a keypress), I need to trigger a keypress of value 13.

(Clarification, I do not want to trigger some event when the enter key is pressed. If I didn't know how to do that, I could find that that's been asked and answered several times on SO. I want the reverse. I am trying to develop a workaround that requires I emulate an 'enter' keypress.)

Derek Henderson
  • 9,388
  • 4
  • 42
  • 71

3 Answers3

57

You can do this -

var e = $.Event( "keypress", { which: 13 } );
$('#yourInput').trigger(e);
Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111
  • 4
    Note however this will simply trigger the event, default behaviors won't actually occur. http://jsfiddle.net/YkLhs/ – Kevin B Jun 20 '13 at 15:42
  • 1
    @KevinB, is there some method by which we can trigger the default behaviors? The evidence is indisputable that this works, yet it's not triggering the behavior I need. – Derek Henderson Jun 20 '13 at 15:47
  • Try looking at it from another direction. Why do you need to simulate this event? – Kevin B Jun 20 '13 at 15:49
  • @KevinB, yesterday I asked this question: http://stackoverflow.com/questions/17197223/is-it-possible-to-paste-a-list-to-a-select2-field-and-test-each-item-in-the-list. As you can see, no answers. But I have noticed that in select2, if you enter a search term that matches and press enter, the item is added to the list of matched objects. Thus, I am setting up a 'paste' event and splitting the pasted list by commas and spaces. I was hoping that if I triggered enter after each token, it would behave as if I had typed in the term and pressed enter, but alas that doesn't seem to work. – Derek Henderson Jun 20 '13 at 15:53
  • From the documentation, all that takes is `$("#selectid").select2("val", ["thefirstvalue","thesecondvalue","thethirdvalue"]);` – Kevin B Jun 20 '13 at 15:57
  • @KevinB, I really wish that were all it takes. :( But alas, that does not work. – Derek Henderson Jun 20 '13 at 16:08
4
 var e = $.Event( "keyup", { keyCode: 13 } );
    $('#yourInput').trigger(e);

Worked for me, instead of 'which', I used 'keyCode'

user1188867
  • 3,726
  • 5
  • 43
  • 69
1

Simulate enter keypress

var e = jQuery.Event("keypress");
        e.which = 13 
        e.keyCode = 13
        $('#email').focus();
        $('#email').trigger(e);

capture enter keypress

$('#email').keypress(function (e) {
if (e.which == '13') {
    alert('code');
}});
Mool Singh
  • 76
  • 3