Billwee
Billwee

Reputation: 7

Allowing only letters for onkeyup function. While also negating keys like PgUp, Del, ArrowLeft etc

I'm very new to Javascript and I have an assignment to create a letter guessing game. I have it all done and wanted to go the extra mile and create an alert when something other than a letter is pressed. I found this great example a day or two ago..

toLowerCase() != key.toUpperCase()

But the input can still be any arrow key and the six keys above it. The onkeyup retuns a string for these and I'm trying to use charAt(1) to single them out. But it's not working.

function isLetter(key) {
  if (key.toLowerCase() != key.toUpperCase() && key.charAt(1) === '') {
    return true;
  } else {
    return false;
  }
}

and the key up function

document.onkeyup = function(event) {
  keyPress = event.key;
  if (!isLetter(keyPress)) {
    return alert('Enter a letter');
  }
}

Upvotes: 0

Views: 85

Answers (2)

XaveScor
XaveScor

Reputation: 113

You need to use the direct code of any input symbol. https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode

const ACode = 65;
const ZCode = 90;
function isLetter(key) {
    return ACode <= key && key <= ZCode;    
}

document.onkeyup = function (event) {
    keyPress = event.keyCode;
    if (!isLetter(keyPress)) {
        return alert('Enter a letter');
    }
}

Upvotes: 0

Hao Wu
Hao Wu

Reputation: 20859

Your approach has a potential bug. Which is the key - and + etc. will also pass the test.

It's probably better to use a regular expression to test the key stroke:

function isLetter(key) {
	// This regular expression tests if the key is only a single character from a to z
	return key.match(/^[a-z]$/);	
}

document.onkeyup = function (event) {
	keyPress = event.key;
	if (!isLetter(keyPress)) {
		return alert('Enter a letter');
	}
}

Upvotes: 1

Related Questions