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);
});
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.
Author by
user1093150
Updated on November 21, 2022Comments
-
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 about 12 yearsWhat is the purpose? Are you just trying to add a newline to the text input?
-
gen_Eric about 12 yearsWhy the enter key, what action would that do? I'd suggest just doing that action.
-
user1093150 about 12 yearsThe 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 about 12 yearsHave you considered triggering the tag feature on blur(), or after some delay? Or a note telling the user to hit Return?
-
-
gen_Eric about 12 yearsWhy do you need
[0]
?.closest
should only ever return 1 element. -
jnoreiga about 12 yearsMaybe 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 about 12 yearsNo, 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 about 12 yearsThe 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 about 12 yearsThe 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