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.

Le Thanh
  • 227
  • 4
  • 10

3 Answers3

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>
Arnauld
  • 5,847
  • 2
  • 15
  • 32
  • 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. – Le Thanh Aug 15 '16 at 13:48
  • Also, if I check (event.key >= 'A' && event.key <= 'Z'), all other keys such as `delete`, `end`, `tab`, so on still in this range. – Le Thanh Aug 15 '16 at 13:56
  • @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. – Arnauld Aug 15 '16 at 14:03
  • Capital characters is now ok. I get special characters' code in this link (https://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? – Le Thanh Aug 15 '16 at 14:20
  • @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](http://www.asciitable.com/) and you should be OK. – Arnauld Aug 15 '16 at 14:27
  • Oh, I understood. It compares string, not by keycode. Thank you! – Le Thanh Aug 15 '16 at 14:28
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>
xerotolerant
  • 1,955
  • 4
  • 21
  • 39
  • 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? – Le Thanh Aug 15 '16 at 13:22
  • http://stackoverflow.com/questions/2257070/detect-numbers-or-letters-with-jquery-javascript 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. – xerotolerant Aug 16 '16 at 01:19
  • 1
    Using regular expression worked in my test. Updated my answer to reflect that. – xerotolerant Aug 16 '16 at 02:18
  • It is ok but I think your way more complex – Le Thanh Aug 17 '16 at 03:52
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);
        }
});
yovche
  • 1
  • 3