javascript tutorial - [Solved-5 Solutions] How to detect pressing enter or keyboard using jQuery ? - javascript - java script - javascript array
Problem:
We would like to detect whether the user has pressed Enter
using jQuery.
How is this possible ? Does it require a plugin ?
Solution 1:
The whole point of jQuery is that we don't have to worry about browser differences. We am pretty sure we can safely go with enter being 13 in all browsers. So with that in mind, we can do this:
$(document).keypress(function(e) {
if(e.which == 13) {
alert('We pressed enter!');
}
});
click below button to copy the code. By JavaScript tutorial team
Solution 2:
We wrote a small plugin to make it easier to bind the "on enter key pressed" a event:
$.fn.enterKey = function (fnc) {
return this.each(function () {
$(this).keypress(function (ev) {
var keycode = (ev.keyCode ? ev.keyCode : ev.which);
if (keycode == '13') {
fnc.call(this, ev);
}
})
})
}
click below button to copy the code. By JavaScript tutorial team
Usage:
$("#input").enterKey(function () {
alert('Enter!');
})
click below button to copy the code. By JavaScript tutorial team
Solution 3:
We couldn't get the code posted by @Paolo Bergantino to work but when we changed it to $(document)
and e.which
instead of e.keyCode
then we found it to work faultlessly.
$(document).keypress(function(e) {
if(e.which == 13) {
alert('We pressed enter!');
}
});
click below button to copy the code. By JavaScript tutorial team
Solution 4:
We found this to be more cross-browser compatible:
$(document).keypress(function(event) {
var keycode = event.keyCode || event.which;
if(keycode == '13') {
alert('We pressed a "enter" key in somewhere');
}
});
click below button to copy the code. By JavaScript tutorial team
Solution 5:
We can do this using the jquery 'keydown' event handle
$( "#start" ).on( "keydown", function(event) {
if(event.which == 13)
alert("Entered!");
});