Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

keypress event not generated in Chrome on ENTER Key?

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?

like image 583
emilly Avatar asked Jan 25 '13 08:01

emilly


People also ask

How do you trigger click event on pressing Enter key?

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.

How do you detect enter press?

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.

How do you call a function on Enter key press?

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.

How can I tell if a key is entered pressed?

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.


2 Answers

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/

like image 56
sdespont Avatar answered Sep 21 '22 13:09

sdespont


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

like image 34
Tim Down Avatar answered Sep 21 '22 13:09

Tim Down