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.)

2

3 Answers 3

57

You can do this -

var e = $.Event( "keypress", { which: 13 } );
$('#yourInput').trigger(e);
6
  • 4
    Note however this will simply trigger the event, default behaviors won't actually occur. jsfiddle.net/YkLhs
    – Kevin B
    Jun 20, 2013 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. Jun 20, 2013 at 15:47
  • Try looking at it from another direction. Why do you need to simulate this event?
    – Kevin B
    Jun 20, 2013 at 15:49
  • @KevinB, yesterday I asked this question: stackoverflow.com/questions/17197223/…. 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. Jun 20, 2013 at 15:53
  • From the documentation, all that takes is $("#selectid").select2("val", ["thefirstvalue","thesecondvalue","thethirdvalue"]);
    – Kevin B
    Jun 20, 2013 at 15:57
4
 var e = $.Event( "keyup", { keyCode: 13 } );
    $('#yourInput').trigger(e);

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

0
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');
}});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.