I would like to detect whether the user has pressed Enter using jQuery.
How is this possible? Does it require a plugin?
EDIT: It looks like I need to use the keypress()
method.
I wanted to know if anyone knows if there are browser issues with that command - like are there any browser compatibility issues I should know about?
The “enter” key is represent by code “13”, check this ASCII charts. To check if an “enter” key is pressed inside a textbox, just bind the keypress() to the textbox. $('#textbox').
Check the event.The keyCode property returns a number for the key that's pressed instead of a string with the key name. When it returns 13, then we know the enter key is pressed.
To trigger a click button on ENTER key, We can use any of the keyup(), keydown() and keypress() events of jQuery. keyup(): This event occurs when a keyboard key is released. The method either triggers the keyup event, or to run a function when a keyup event occurs.
I 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); } }) }) }
Usage:
$("#input").enterKey(function () { alert('Enter!'); })
The whole point of jQuery is that you don't have to worry about browser differences. I am pretty sure you can safely go with enter being 13 in all browsers. So with that in mind, you can do this:
$(document).on('keypress',function(e) { if(e.which == 13) { alert('You pressed enter!'); } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With