Oblivious290
Oblivious290

Reputation: 33

How do I make onkeyup only be an alphabet key?

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

Answers (3)

jerome
jerome

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

Jan
Jan

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

jake
jake

Reputation: 1264

Check the ASCII code:

if (event.keyCode >= 65 && event.keyCode <= 90) {
    console.log("input was a-z");
}

Upvotes: 2

Related Questions