convert from "onkeypress" to "addeventlistener("keypress",()=>{})

Viewed 205

I have the following line of JS written into my html on an input tag. I'm in class learning about separation of concerns and that we shouldn't put JS into our html. I've been trying to figure out a way to convert this lines:

onkeypress="return (event.charCode >= 65 && event.charCode <= 90) || (event.charCode >= 97 && event.charCode <= 122) || event.charCode == 32;"

To something like this:

document.querySelector("#login-first-name").addEventListener("keypress",function(event){
  return (event.charCode >= 65 && event.charCode <= 90) || (event.charCode >= 97 && event.charCode <= 122) || event.charCode == 32;
});

Any insight would be great.

1 Answers

You need to add parameter event like addEventListener("keypress", (event)=>{ and if you want to use this then use function like addEventListener("keypress", function(event) {

After some research found that with document.querySelector("#login-first-name").addEventListener("keypress" need to assign event.returnValue instead of return. For more information refer this. Updated code also.

Check it below.

document.querySelector("#login-first-name").addEventListener("keypress", (event) => {
  event.returnValue = (event.charCode >= 65 && event.charCode <= 90) || (event.charCode >= 97 && event.charCode <= 122) || event.charCode == 32;
});

document.querySelector("#login-first-name").addEventListener("keyup", function() {
  this.value = this.value.charAt(0).toUpperCase() + this.value.slice(1);
});
<input id='login-first-name' />

Related