10

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.

Marco Prins
  • 7,189
  • 11
  • 41
  • 76
  • Already answered here http://stackoverflow.com/questions/3276794/jquery-or-pure-js-simulate-enter-key-pressed-for-testing – Ruslan Bes Apr 09 '14 at 07:48
  • @MarcoPrins ok just let me now what you wish aftersimulating the enter button being press , do u wish to call any function after that? – anam Apr 09 '14 at 08:48

4 Answers4

11

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

Sridhar R
  • 20,190
  • 6
  • 38
  • 35
  • 2
    This is not what I'm looking for @Sridhar R . This will fire events when enter is pressed. I want to **press** enter (effectively) with jQuery – Marco Prins Apr 09 '14 at 07:56
5

Try this:

$('input').trigger(
  jQuery.Event('keydown', { which: 13 })
);
executable
  • 3,365
  • 6
  • 24
  • 52
corners
  • 151
  • 2
0

try using .trigger() .Docs are here

Aameer
  • 1,366
  • 1
  • 11
  • 30
-2

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

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

  • Hello. Welcome to SO. Consider making a [Tour](https://stackoverflow.com/tour); this will help understand how to answer questions. Please, provide more information about what your solution is working on in that case. – Diesan Romero Jul 05 '21 at 14:36