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.
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.
Keycode 13 is the Enter key.
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”.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With