Reputation: 33
I'm making a letter guessing game and I want the onkeyup
to only accept alphabet keys.
document.onkeyup = function (event) {
var userGuess = event.key;
}
Upvotes: 3
Views: 526
Reputation: 33
Since keyCode is being deprecated, a slightly more modern approach could be something like this...
window.addEventListener('keyup', event => {
if (event.key >= 'a' && event.key <= 'z') {
// do something
}
}
Upvotes: 1
Reputation: 2853
Another option is to get the keycode
from the which
-property of the event
and translate it to a char
. Then you can test the char with regex.
document.addEventListener('keyup', function (event) {
let char = String.fromCharCode(event.which);
if (/[a-z]/i.test(char)) {
// Do something
console.log(char);
}
});
Press any key!
Upvotes: 3
Reputation: 1264
Check the ASCII code:
if (event.keyCode >= 65 && event.keyCode <= 90) {
console.log("input was a-z");
}
Upvotes: 2