1

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.

2
  • you can use match() to make sure only letters are passed by using a regex: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Nov 30, 2017 at 0:12
  • if (event.keyCode >= 65 && event.keyCode <= 90) { run code within here } else { guessesList.pop(userChoice); } ^^for future users, this is what I ended up using, with my page entered within the if function. Thanks everybody who commented with helpful info! Commented Dec 2, 2017 at 22:10

3 Answers 3

1

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)" />

Sign up to request clarification or add additional context in comments.

1 Comment

Please note event.keyCode is depreciated (KeyboardEvent.keyCode). It's better to use event.key instead (KeyboardEvent.key).
0

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)" />

1 Comment

Please note event.keyCode is depreciated (KeyboardEvent.keyCode). It's better to use event.key instead (KeyboardEvent.key).
0

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]+" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.