My application requires an input from users, on entering a value in a textbox, users hit Enter (Return Key) and this calls a buttons onclick event. This works fine in IE, FF but not Chrome. On enter in chrome, keypress event is not generated Here is my code snippet
$('#myDiv').keypress(function (e) {
alert("Key pressed");
if (e.keyCode == $.ui.keyCode.ENTER) {
alert("enter pressed");
}
});
Could anyone provide input on this?
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.
To check whether user pressed ENTER key on webpage or on any input element, you can bind keypress or keydown event to that element or document object itself. Then in bind() function check the keycode of pressed key whether it's value is 13 is not.
You can execute a function by pressing the enter key in a field using the key event in JavaScript. If the user presses the button use the keydown to get know its enter button or not. If it enters the key then call the JavaScript function.
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'). keypress(function(event){ var keycode = (event.
Cross-browsers method :
$('#myDiv').keydown( function(e) {
var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
if(key == 13) {
e.preventDefault();
alert("enter pressed");
}
});
Tested on Chrome 24 : http://jsfiddle.net/PTauw/1/
keypress
is the correct event for detecting which character has been typed (although in this particular case, that of detecting the enter key, keydown
would work just as well). However, how to get the character typed in a keypress event is inconsistent between browsers, so jQuery normalizes on the which
property. Here's what you want:
$('#myDiv').keypress(function (e) {
alert("Key pressed");
if (e.which == $.ui.keyCode.ENTER) {
alert("enter pressed");
}
});
The definitive reference for key events: http://unixpapa.com/js/key.html
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