Simulate Pressing the Enter Key with jQuery

15,165

Solution 1

$("input").blur(function() {
    var e = jQuery.Event("keydown");
    e.which = 13; // Enter
    $("input").trigger(e);
});

Demo

Solution 2

Based on your comment

The reason is that I have a field that lets users enter "tags", but sometimes they dont realize that they have to hit Enter or Tab after adding a tag...they just click off the field and it does not create the tag..

Try,

$("input").blur( /* Fx that adds the Tag*/);

Note: You may need to revise the keydown event handler for tab, because the .blur will be triggered when you hit tab.

Share:
15,165
user1093150
Author by

user1093150

Updated on November 21, 2022

Comments

  • user1093150
    user1093150 over 1 year

    I'm trying to simulate the user hitting the enter key when they leave a input field (.blur). So very basically, on blur, it simulates that the user actually pressed the ENTER key on their keyboard...Any ideas on how to do this?

    • Brian Driscoll
      Brian Driscoll about 12 years
      What is the purpose? Are you just trying to add a newline to the text input?
    • gen_Eric
      gen_Eric about 12 years
      Why the enter key, what action would that do? I'd suggest just doing that action.
    • user1093150
      user1093150 about 12 years
      The reason is that I have a field that lets users enter "tags", but sometimes they dont realize that they have to hit Enter or Tab after adding a tag...they just click off the field and it does not create the tag..
    • Surreal Dreams
      Surreal Dreams about 12 years
      Have you considered triggering the tag feature on blur(), or after some delay? Or a note telling the user to hit Return?
  • gen_Eric
    gen_Eric about 12 years
    Why do you need [0]? .closest should only ever return 1 element.
  • jnoreiga
    jnoreiga about 12 years
    Maybe he doesn't have a form and is doing it with an ajax request that then navigates to a returned url. We don't know much about what his code looks like
  • user1093150
    user1093150 about 12 years
    No, I definitely want it to happen on blur. I want it to be 'as if' the user hit enter, as soon as they leave the input field
  • ThiefMaster
    ThiefMaster about 12 years
    The jQuery .submit() function will not actually submit the form - at least it used to be like that; so i'm calling the native DOM method.
  • user1093150
    user1093150 about 12 years
    The problem is that I'm using an ExpressionEngine module for this seems to do all of this and I'm trying to modify it 'after the fact' without hacking the module