I'd like to have Javascript respond to a keypress or keydown event from only the numeric keypad Enter key, not the usual Enter key. They both seem to generate the same event data according to the demo in the jQuery keypress docs, so I'm not sure it's possible.
They do generate the same keystroke data, at the level of abstraction that JavaScript has access to. Remember, JavaScript lives in a sandbox (the browser) and has no direct access to the underlying hardware (there are plenty of platforms that don't have a numeric keypad at all, but do have a browser).
This cannot be done.
EDIT:
Support for this has been added for some browsers but does not seem to be universal (see the other answer).
it is possible to detect the numpad Enter as seperate key nowadays. With the KeyboardEvent.location property. this way you can firstly check the keycode 13 and after if the key is on the numpad which devines the numpad enter.
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/location
example:
window.onkeydown=function(ev)
{
var e= ev || window.event,
key = e.keyCode
if ((key===13) && (e.location===3)) {
console.log("got ya");
console.log(e.location);
}
}
Related
I'm trying to strip jQuery out of an existing codebase as part of a modernization/optimization initiative. There are a few places where something needs to happen when a user hits the enter key while in a text input. Previously, we accomplished this with the following:
$("#loginInput").on("keypress", e => {
if (e.which == 13) {
// if key pressed was enter...
login();
}
});
However, reading through the keyboard event APIs here I've found that most of the commonly used APIs are deprecated, such as KeyboardEvent.which and KeyboardEvent.keyCode.
Even though these properties are still available in most browsers, I feel uncomfortable using deprecated APIs. What should I use instead?
I think you want event.key. It seems to be widely supported.
The "key" property gives the character reflected by the user interaction with the keyboard, taking into account all the meta keys involved (shift, ctrl, etc).
So to check for the carriage return character (13), you'd use
if (event.key === "Enter") {
// enter key was pressed
}
edit updated to reflect the somewhat astonishing fact that the "key" property is set to the string "Enter" when that key triggers the event.
Related: JavaScript KeyCode vs CharCode
Here is some code you can try at home or in a jsfiddle:
el.addEventListener( 'keyup', function( e ) {
console.log( 'Keyup event' );
console.log( e.keyCode );
} );
el.addEventListener( 'keypress', function( e ) {
console.log( 'Keypress event' );
console.log( e.keyCode );
} );
Why is the keyCode different?
I can understand why one should use keypress only, but what I don't understand is how two key events, given the same hit key on the keyboard, give different keyCodes.
PS: I'm not worrying about legacy browsers support, I tried this in Chrome and was surprised, and couldn't find an explanation.
The events are for completely different purposes. Use keyup and keydown for identifying physical keys and keypress for identifying typed characters. The two are fundamentally different tasks with different events; don't try to mix the two. In particular, keyCode on keypress events is usually redundant and shouldn't be used (except in older IE, but see the linked document below for more on that); for printable keypresses it's usually the same as which and charCode, although there is some variation between browsers.
Jan Wolter's article on key events, already linked to in another answer, is the definitive word on this subject for me and has tables describing what each of the different properties returns for each type of key event and each browser.
There is a good article on quirksmode.org answering exactly that question. You might also want to look at Unixpapa's results.
Well, I stumbled upon one difference when i was trying to copy user's entry from one input of the form to some other part of the form , which I had locked for my for users to edit.
What i found was, that whenever a user moved to the next label using key upon completing the input, one last keyboard entry was missed in the copied entry when I used eventListener to keypress and this got resolved on using keyup.
So, in conclusion Keypress listens to the state at the instant when the key was pressed, leaving aside the result of keypress, whereas keyup listens to the system status after the key has been pressed and includes the result of the keypress.
$(document).keydown(function (event)
{
alert(event.which);
});
For the semicolon key, ;, this gives 59 in Firefox and 186 in Chrome. However, from the jQuery reference page for the keydown event, it says
"While browsers use differing properties to store this information, jQuery normalizes the .which property so you can reliably use it to retrieve the key code. This code corresponds to a key on the keyboard, including codes for special keys such as arrows."
Am I missing something?
The which property is a "one stop shop" for which key was pressed, allowing you to ignore the differences between the keyCode and charCode properties. That is the "normalization" that jQuery provides.
The difference in the value of which comes down to a difference between the way the various browsers supply the information - so you'll have to write code to handle the different values that come back. There are a few references to this behavior online.
A quick Google search says you will simply have to test for both. This is a consistent inconsistency with Firefox.
I don't know about jQuery but I'd suggest sticking to keypress events for typing keys and only using keydown events for special keys such as arrows.
Here is the entirety of the "normalization" that jQuery does:
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
Looks like it just gets keyCode if charCode doesn't exist. And charCode is only used if event.which doesn't already exist. It doesn't change the numbers around to make them consistent.
I'm new to dealing with BlackBerry devices. I'm currently running into a JavaScript issue on a 9700 and trapping keypress events and getting a proper keycode.
I have this javascript:
function numbersonly(e) {
var key
if(window.event) {
key = window.event.keyCode; // IE
}else{
key = e.which; // Firefox
}
alert('keycode : ' + key);
}
And it's attached to an input field via an unobtrusive addEvent script.
On a standard desktop browser (Firefox and IE), it does what you'd think it does...pressing a key will show the keycode via the alert.
On a blackberry, however, pressing a key does one of two things:
if the key presses is the numbers 1 through 9, nothing happens.
if it's any other key, the keyCode is 'undefined'.
Any idea what's going on? I assume it's a limitation of the BlackBerry JavaScript support.
UPDATE:
Tested this on a 9800 Simulator as well, which is running OS6. Problem doesn't exist there. So this is either an issue with BlackBerry OS5 or BlackBerry's physical keyboard.
I'm not sure if the event variable is set when you add an inline event handler.
Have you tried setting the event-handler from javascript. So something like
document.getElementById('mytextelement').onkeypress = keytest;
Try using e.keyCode instead of e.which
I have an input like this
<input id="guestCard" name="guestCard" onkeypress="transform(event)" type="text" value="" />
and I want to transform the key pressed on a keyboard regardless of which language settings to english character. E.g. when I press on czech keyboard + (with keycode 43) , I want to get 1 (with keycode 49).
Is there some standard way to do this? How would the function transform look like?
Alternatively I want the same functionality but using ajax (on asp.net mvc). Any ideas there?
Thanks in advance.
As far as I am aware, JavaScript is not locale aware - so you would need to somehow detect or have the user pick the appropriate transform mapping (in this case, perhaps a radio button for czech as the source and U.S. ASCII as the destination). Once that is taken care of, your function could be something like:
function transform(event) {
var code = (event.charCode) ? event.charCode : event.keyCode; // cross-browser happy
switch (code) {
case 43 : return "1";
}
}
There is a great test page to see how keyCode/charCode properties and the onKeyDown/Press/Up events behave in different browsers. http://asquare.net/javascript/tests/KeyCode.html
I doubt there is one but to create it, create an associative array, add some JS to a text field which saves the two values in the array and then press every key on the keyboard. After that, you can dump the array somewhere and use this as a constant in your code.
But be warned: Almost all users will have problems when they don't get the character on the screen which they've typed on the keyboard.
Trimack -
I think you are using the wrong event. You need onkeydown, and use the keyCode property of event.