Radex
Radex

Reputation: 8587

Detect keyCode issue wrong value

I need to detect when user select on keyboard letter ] KeyCode: 221 and return the letter ] on the dom.

My problem is:

The value returned by event.keyCode is different if the event is returned from an input element or document.

Also

testing the following issue on Chrome Version 55.0

I get for input: event.keyCode: 93 - String.fromCharCode: ]

I get for document: event.keyCode: 221 - String.fromCharCode: Ý

and on Firefox 50.1.0

I get for input: event.keyCode: 0 - String.fromCharCode:

I get for document: event.keyCode: 221 - String.fromCharCode: Ý

I would need to know:

Notes: I am using a ENG United State international keyboard (could this be relevant?).

var input = document.getElementById('input');
var result = document.getElementById('result');
input.addEventListener('keypress', function(event) {
  result.innerHTML = `event.keyCode: ${event.keyCode} - String.fromCharCode: ${String.fromCharCode(event.keyCode)}`;

});

var resultDocument = document.getElementById('resultDocument');

document.addEventListener('keydown', function(event){
  resultDocument.innerHTML = `event.keyCode: ${event.keyCode} - String.fromCharCode: ${String.fromCharCode(event.keyCode)}`;
});
<input id="input" type="text" size="40">
<div id="result"></div>

<h1>On document</h1>
<div id="resultDocument"></div>

Upvotes: 0

Views: 2219

Answers (3)

Ajay Varghese
Ajay Varghese

Reputation: 769

You are using keypress event for getting keycode from input and keydown from document. Keyup and Keydown always returns the unicode value of the uppercase version of a character. So if if you want it to be case sensitive, I recommend to use Keyup, otherwise you can use keypress.

http://www.javascriptkit.com/jsref/eventkeyboardmouse.shtml Check it out for more info. Cheers

Upvotes: 0

junkfoodjunkie
junkfoodjunkie

Reputation: 3178

This works fine, it seems (at least it gives the same answer in Firefox, haven't tested in other browsers)

var input = document.getElementById('input');
var result = document.getElementById('result');
input.addEventListener('keypress', function(event) {
  result.innerHTML = `event.which: ${event.which} - String.fromCharCode: ${String.fromCharCode(event.which)}`;
});

var resultDocument = document.getElementById('resultDocument');

document.addEventListener('keypress', function(event){
  resultDocument.innerHTML = `event.which: ${event.which} - String.fromCharCode: ${String.fromCharCode(event.which)}`;
});
<input id="input" type="text" size="40">
<div id="result"></div>

<h1>On document</h1>
<div id="resultDocument"></div>

Upvotes: 0

Igor Zalutski
Igor Zalutski

Reputation: 160

Event.keyCode is deprecated and inconsistent across browsers, use Event.key instead if available. If not, your best bet would be to use a library such as Keypress. jQuery will also do.

Upvotes: 2

Related Questions