41

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

61

You can do this -

var e = $.Event( "keypress", { which: 13 } ); $('#yourInput').trigger(e); 
Sign up to request clarification or add additional context in comments.

6 Comments

Note however this will simply trigger the event, default behaviors won't actually occur. jsfiddle.net/YkLhs
@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.
Try looking at it from another direction. Why do you need to simulate this event?
@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.
From the documentation, all that takes is $("#selectid").select2("val", ["thefirstvalue","thesecondvalue","thethirdvalue"]);
|
5
 var e = $.Event( "keyup", { keyCode: 13 } ); $('#yourInput').trigger(e); 

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

Comments

2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.