Marco Prins
Marco Prins

Reputation: 7419

Press the enter key in a text box with jQuery

How can I mimic pressing the enter button from within a <input>, using jQuery?

In other words, when a <input> (type text) is in focus and you press enter, a certain event is triggered. How can I trigger that event with jQuery?

There is no form being submitted, so .submit() won't work

EDIT

Okay, please listen carefully, because my question is being misinterpreted. I do NOT want to trigger events WHEN the enter button is pressed in textbox. I want to simulate the enter button being pressed inside the textbox, and trigger this from jQuery, from $(document).ready. So no method involving on.('keypress')... or stuff like that is what I'm looking for.

Upvotes: 10

Views: 27004

Answers (4)

Akash Rathore
Akash Rathore

Reputation: 1

Instead of using {which:13} try using {keyCode:13}.

$('input').trigger(jQuery.Event('keydown', {keyCode:13}));

Upvotes: -2

corners
corners

Reputation: 151

Try this:

$('input').trigger(
  jQuery.Event('keydown', { which: 13 })
);

Upvotes: 5

Sridhar R
Sridhar R

Reputation: 20408

Use keypress then check the keycode

Try this

$('input').on('keypress', function(e) {
    var code = e.keyCode || e.which;
    if(code==13){
        // Enter pressed... do anything here...
    }
});

OR

e = jQuery.Event("keypress")
e.which = 13 //choose the one you want
    $("#test").keypress(function(){
     alert('keypress triggered')
    }).trigger(e)

DEMO

Upvotes: 11

Aameer
Aameer

Reputation: 1376

try using .trigger() .Docs are here

Upvotes: 0

Related Questions