How to check KeyboardEvent.key in specific range in Javascript
Asked Answered
A

3

9

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.

Additive answered 15/8, 2016 at 12:59 Comment(0)
C
10

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>
Chante answered 15/8, 2016 at 13:29 Comment(6)
It corrects for number and character. However, I check it with (event.key >= ';' && event.key <= '`') (range from 186 to 192), it gets other key outside range.Additive
Also, if I check (event.key >= 'A' && event.key <= 'Z'), all other keys such as delete, end, tab, so on still in this range.Additive
@LeThanh - Please see my updated answer for another example with capital letters. Regarding your first comment, I don't get it. Characters ";" to "`" are covering the range 59 to 96.Chante
Capital characters is now ok. I get special characters' code in this link (css-tricks.com/snippets/javascript/javascript-keycodes), it tell me semi-colon (186), equal-sign(187), comma(188), dash(189), period(190), forward slash (191), and grave accent (192). Can you test again?Additive
@LeThanh - I see. The table you're referring to contains non-standard codes that were specific to keyCode and may even vary from one browser to another. Please refer to the standard ASCII table and you should be OK.Chante
Oh, I understood. It compares string, not by keycode. Thank you!Additive
T
3

According to https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key

"The KeyboardEvent.key read-only property returns the value of a key or keys pressed by the user."

The values that get returned are strings. You would probably have to remain using key.code if you want to check range.

Alternatively you could use switch statements like in the example on mdn

switch (event.key) {
    case "ArrowDown":
      // Do something for "down arrow" key press.
      break;
    case "ArrowUp":
      // Do something for "up arrow" key press.
      break;
    case "ArrowLeft":
      // Do something for "left arrow" key press.
      break;
    case "ArrowRight":
      // Do something for "right arrow" key press.
      break;
    case "Enter":
      // Do something for "enter" or "return" key press.
      break;
    case "Escape":
      // Do something for "esc" key press.
      break;
    default:
      return; // Quit when this doesn't handle the key event.
  }

Or event still make an array like

 var validKeys = ["ArrowDown", "ArrowUp", ...]

and then check to see if the event.key is in the array.

Finally you could use regular expressions

This should work

<script type="text/javascript">

      document.addEventListener('keydown', function(event){
        var charTyped = event.key;
        if (/^[a-z\d]$/i.test(charTyped)) {
            console.log("Letter or number typed: " + charTyped);
        }
      })


</script>
Trustless answered 15/8, 2016 at 13:15 Comment(4)
Code will be long if I want check character a-z0-9 and some special key. I don't want use deprecated properties such as event.keyCode. The property event.code return DOM string, so it can not use also. Is there any other way?Additive
#2257570 This answer uses a regular expression, you might be able to check the key against that. I'll read a bit more and get back to you.Trustless
Using regular expression worked in my test. Updated my answer to reflect that.Trustless
It is ok but I think your way more complexAdditive
W
0

The regex code for letters only, capital letters included, is like this

/^[a-z\D]
  • \d - used when you want to include numbers
  • \D - exclude numbers

So, the entire code block would look like this:

window.addEventListener('keydown', e => {
  
  const letterTyped = e.key;
        if (/^[a-z\D]$/i.test(letterTyped)) {
            console.log("Letter pressed: " + letterTyped);
        }
});
Will answered 13/7, 2023 at 15:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.