5

So I know that we can find if a key was pressed, and we can know which key was pressed by using javascript.

To determine if a key was down or pressed we can just use jQuery

$( "#some id" ).keydown(function() 

or

$( "#m" ).keypress(function() 

But this does not work pretty good for me. I am trying to determine if a letter, or a number were pressed.

BUT, to be efficient, I don't want to check with a big if (or a for loop, worse) whether the key pressed was a letter or a character(by comparing and checking the character code)

Is there like a built in javascript function that determines if a number was pressed or a letter was pressed? is there an efficient way of doing this? or I am just overcomplicating things?

myselfmiqdad
  • 2,518
  • 2
  • 18
  • 33
Kevin Cohen
  • 1,211
  • 2
  • 15
  • 22
  • Yup, pretty sure peopel have done this before. – Jonathan Jan 08 '16 at 23:41
  • 1
    Check by ranges... Letters are all next to each other. So are numbers. You only need a couple if clauses – Araymer Jan 08 '16 at 23:42
  • you could just check which range of codes are numbers and which are letters. I think numbers range from 48-57 and letters from 65-90 and num pad keys from 96-105 – chrisarton Jan 08 '16 at 23:42
  • According to these answers you have to map the keyboard : http://stackoverflow.com/a/302161/3531064 http://stackoverflow.com/a/979686/3531064 – Matthéo Geoffray Jan 08 '16 at 23:43
  • @AdamBuchananSmith I would not agree. I know how to determine which key was pressed. I was looking specifically if there was a faster/cleaner way of determining a number or letter each time I would type. – Kevin Cohen Jan 08 '16 at 23:57
  • @KevinCohen good thing SO is a democracy, it will be voted on. We will see ;) – Adam Buchanan Smith Jan 08 '16 at 23:58
  • 1
    It depends on your definition and your purpose -- ultimately, you might want to see what the character's [Unicode General Category](https://en.wikipedia.org/wiki/Unicode_character_property#General_Category) is. Everything else is just making assumptions like "surely you can't type ä on a keyboard". – Ulrich Schwarz Jan 09 '16 at 07:23

1 Answers1

11

Simply check the range:

if (event.keyCode >= 48 && event.keyCode <= 57) {
    // Number
} else if (event.keyCode >= 65 && event.keyCode <= 90) {
    // Alphabet upper case
} else if (event.keyCode >= 97 && event.keyCode <= 122) {
    // Alphabet lower case
}

Here is a detailed answer to a similar question. Good reference.

The Number pad code is the same as that above the keyboard: Reference from Keyboard Keys and Key Code Values


UPDATE:

Use the .key

var x = event.key; // instead of event.keyCode

and

if (x >= 48 && x <= 57) {
    // Number
} else if (x >= 65 && x <= 90) {
    // Alphabet upper case
} else if (x >= 97 && x <= 122) {
    // Alphabet lower case
}
myselfmiqdad
  • 2,518
  • 2
  • 18
  • 33