Reputation: 191
Any tips on how to write a JS function to check user input before posting to HTML page?
Using this so far:
document.onkeyup = function(event){
if (event.key >= 65 && event.key <=90){
guessesList.push(userChoice);
}
};
but doesn't seem to do anything when I refresh the page. The input needs to be only a letter, not a number or other input key.
Upvotes: 1
Views: 1790
Reputation: 16384
You can add pattern
attribute with regexp (it should be [A-Za-z]+
in your case) to your input
element, and then check validity using inputElement.checkValidity()
method, which returns true
or false
, which means is your input valid or invalid:
function validate(inputEl) {
console.log(inputEl.checkValidity());
};
<input type="text" id="test" onkeyup="validate(this)" pattern="[A-Za-z]+" />
Upvotes: 0
Reputation: 68933
You are trying to compare each character with keyCode
. Thus you need to change:
event.key
to event.keyCode
You can do something like the following:
function myFunction(event){
console.log(event.keyCode)
if (event.keyCode >= 65 && event.keyCode <=90){
//guessesList.push(userChoice);
}
};
<input type="text" placeholder="Sample text" id="test" onkeyup="myFunction(event)" />
Upvotes: 1
Reputation: 670
You can use keyCode
property.
function myFunction(event){
if (event.keyCode >= 65 && event.keyCode <=90){
console.log(event.key);
}
};
<input type="text" placeholder="Sample text" id="test" onkeyup="myFunction(event)" />
Upvotes: 0