Reputation: 10530
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?
Upvotes: 17
Views: 31306
Reputation: 37233
Chrome seems to be working with ENTER
key and not 13
.
this works for me on all browsers including CHROME
.
$('#myDiv').keydown(function(e) {
if ((e.which == 13) || (e.which == keyCode.ENTER)) {
alert("enter pressed");
}
Upvotes: -1
Reputation: 324477
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
Upvotes: 6
Reputation: 6156
This link might be helpful for you...
Api Jquery Key Press
or try with this code
Change keypress to keydown:
$('#myDiv').keydown(function(e) {
// your logic
alert("Key pressed");
if (e.keyCode == $.ui.keyCode.ENTER) {
alert("enter pressed");
}
});
Upvotes: 0
Reputation: 14025
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/
Upvotes: 27