Is there any event in Jquery that's triggered only if the user hits the enter button in a textbox? Or any plugin that can be added to include this? If not, how would I write a quick plugin that would do this?
11 Answers
You can wire up your own custom event
$('textarea').bind("enterKey",function(e){
//do stuff here
});
$('textarea').keyup(function(e){
if(e.keyCode == 13)
{
$(this).trigger("enterKey");
}
});
-
11It's worth noting that in a scenario of enter detection to prevent form submission, "keyup" event is not optimal because the form detects the submit on keydown. Thus "keydown" or "keypress" might be better in that case. Apr 12, 2017 at 8:19
-
8
-
Different browsers has different
e.keyCode
for some keys, better to usee.which
, this will guarantee that you will handle same button on every browser Feb 1, 2020 at 15:09
$('#textbox').on('keypress', function (e) {
if(e.which === 13){
//Disable textbox to prevent multiple submit
$(this).attr("disabled", "disabled");
//Do Stuff, submit, etc..
//Enable the textbox again if needed.
$(this).removeAttr("disabled");
}
});
-
8Thanks - This solution fitted my use case. However, it's worth noting that once any processing is done, you may want to add ` $(this).removeAttr("disabled");` to re-enable the textbox. Feb 2, 2016 at 1:19
Here is a plugin for you: (Fiddle: http://jsfiddle.net/maniator/CjrJ7/)
$.fn.pressEnter = function(fn) {
return this.each(function() {
$(this).bind('enterPress', fn);
$(this).keyup(function(e){
if(e.keyCode == 13)
{
$(this).trigger("enterPress");
}
})
});
};
//use it:
$('textarea').pressEnter(function(){alert('here')})
-
Nice. Much simpler than that URL I posted. I wonder what the heck the article I posted is all about & why it takes so much code.. Jun 29, 2011 at 17:10
-
1Too late, I've already written my own :P. It also does the same job in less lines.. also, using the
$
variable for the plugin isn't a good idea as it can cause conflicts.– AliJun 29, 2011 at 17:30 -
@Neal, do you know how the code of the plugin I posted in the accepted answer would have to be changed, so that one could do
$("#myInput").bind('click, onEnter', myCallback);
and it would work without needing anything else?– AliJun 29, 2011 at 17:53 -
1
-
@Neal Amazing solution man. I just had copy that function! thanks! Mar 24, 2013 at 11:08
heres a jquery plugin to do that
(function($) {
$.fn.onEnter = function(func) {
this.bind('keypress', function(e) {
if (e.keyCode == 13) func.apply(this, [e]);
});
return this;
};
})(jQuery);
to use it, include the code and set it up like this:
$( function () {
console.log($("input"));
$("input").onEnter( function() {
$(this).val("Enter key pressed");
});
});
-
2Nice, I'd call the callback using
func.apply(this)
, that way inside the callback function you can usethis
as normal to access the element on which the event was triggered.– AliJun 29, 2011 at 17:52 -
yeah, good point about func.apply(this), had not even considered that.– jzillaJun 29, 2011 at 18:09
-
Nice and concise, but I'd add that stopping propagation and defaults would be a good idea in most cases, to prevent any form submission. Just add
e.preventDefault(); e.stopPropagation();
inside theif (e.keyCode)
bit. Dec 19, 2014 at 15:59
It should be well noted that the use of live()
in jQuery has been deprecated since version 1.7
and has been removed in jQuery 1.9
. Instead, the use of on()
is recommended.
I would highly suggest the following methodology for binding, as it solves the following potential challenges:
- By binding the event onto
document.body
and passing $selector as the second argument toon()
, elements can be attached, detached, added or removed from the DOM without needing to deal with re-binding or double-binding events. This is because the event is attached todocument.body
rather than$selector
directly, which means$selector
can be added, removed and added again and will never load the event bound to it. - By calling
off()
beforeon()
, this script can live either within within the main body of the page, or within the body of an AJAX call, without having to worry about accidentally double-binding events. - By wrapping the script within
$(function() {...})
, this script can again be loaded by either the main body of the page, or within the body of an AJAX call.$(document).ready()
does not get fired for AJAX requests, while$(function() {...})
does.
Here is an example:
<!DOCTYPE html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var $selector = $('textarea');
// Prevent double-binding
// (only a potential issue if script is loaded through AJAX)
$(document.body).off('keyup', $selector);
// Bind to keyup events on the $selector.
$(document.body).on('keyup', $selector, function(event) {
if(event.keyCode == 13) { // 13 = Enter Key
alert('enter key pressed.');
}
});
});
</script>
</head>
<body>
</body>
</html>
If your input is search
, you also can use on 'search'
event. Example
<input type="search" placeholder="Search" id="searchTextBox">
.
$("#searchPostTextBox").on('search', function () {
alert("search value: "+$(this).val());
});
//Short and simple solution
$(document).ready(function(){
$('#TextboxId').keydown(function(event){
if (event.which == 13){
//body or action to be performed
}
});
});
-
1Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.– Community BotSep 17, 2021 at 9:16
HTML Code:-
<input type="text" name="txt1" id="txt1" onkeypress="return AddKeyPress(event);" />
<input type="button" id="btnclick">
Java Script Code
function AddKeyPress(e) {
// look for window.event in case event isn't passed in
e = e || window.event;
if (e.keyCode == 13) {
document.getElementById('btnEmail').click();
return false;
}
return true;
}
Your Form do not have Default Submit Button
Another subtle variation. I went for a slight separation of powers, so I have a plugin to enable catching the enter key, then I just bind to events normally:
(function($) { $.fn.catchEnter = function(sel) {
return this.each(function() {
$(this).on('keyup',sel,function(e){
if(e.keyCode == 13)
$(this).trigger("enterkey");
})
});
};
})(jQuery);
And then in use:
$('.input[type="text"]').catchEnter().on('enterkey',function(ev) { });
This variation allows you to use event delegation (to bind to elements you haven't created yet).
$('body').catchEnter('.onelineInput').on('enterkey',function(ev) { /*process input */ });
I could not get the keypress
event to fire for the enter button, and scratched my head for some time, until I read the jQuery docs:
"The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except that modifier and non-printing keys such as Shift, Esc, and delete trigger keydown events but not keypress events." (https://api.jquery.com/keypress/)
I had to use the keyup
or keydown
event to catch a press of the enter button.
<form name="searchForm" id="searchForm" onsubmit="doSomething(event)">
<input type="text" name="search" id="search">
</form>
<script>
function doSomething(event){
let $val = $('form#searchForm input[name="search"]').val();
console.log($val);
event.preventDefault();
}
</script>
One simple way it can be done in this way. Enter text or number, hit enter key and get the entered input value.