Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check KeyboardEvent.key in specific range in Javascript

In Javascript, I have callback function for keydown event. I use keyCode and which properties to detect which keys user pressed.

var keyPressed = event.keyCode || event.which;
if (keyPressed > 47 && keyPressed < 58) {
    //do something
}

It works well. However, this properties are deprecated, I switch to key property. When I replace code, it does not work correctly.

if (event.key > 47 && event.key < 58) {
        //do something
}

I can't check user's pressed key in range.

like image 906
Le Thanh Avatar asked Aug 15 '16 12:08

Le Thanh


People also ask

How do you check if a key is pressed in JavaScript?

Using JavaScript In plain JavaScript, you can use the EventTarget. addEventListener() method to listen for keyup event. When it occurs, check the keyCode 's value to see if an Enter key is pressed.

What is e keyCode === 13?

Keycode 13 is the Enter key.

How do you check if a key is a number JavaScript?

In JavaScript, there are two ways to check if a variable is a number : isNaN() – Stands for “is Not a Number”, if variable is not a number, it return true, else return false. typeof – If variable is a number, it will returns a string named “number”.


1 Answers

For printable characters, .key() returns a non-empty Unicode character string containing the printable representation of the key.

Essentially: for ASCII characters, you get the character itself rather than its ASCII code.

So, for digits you could just do:

var myInput = document.getElementsByTagName('input')[0];

myInput.addEventListener("keydown", function(event) {
  if(event.key >= "0" && event.key <= "9") {
    console.log('digit: ' + event.key);
  }
});
<input>

For letters, you'll also have to check that .key() returns a single character because a non-printable key such as delete will be encoded as "Delete", which would pass the test "Delete" >= "A" && "Delete" <= "Z".

var myInput = document.getElementsByTagName('input')[0];

myInput.addEventListener("keydown", function(event) {
  if(event.key.length == 1 && event.key >= "A" && event.key <= "Z") {
    console.log('capital letter: ' + event.key);
  }
});
<input>
like image 137
Arnauld Avatar answered Sep 20 '22 13:09

Arnauld