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?
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
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
}