Home > Mobile >  how do I remove a keypress event added in <html>?
how do I remove a keypress event added in <html>?

Time:01-03

My html code is as following:

<input type="text" id="emp" onkeypress="return (event.charCode > 64 && 
event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" >

It forbids input of any number in the input field. Now, I want to remove this keypress event on meeting a certain condition in my js. So I tried executing:

if(condition)
    document.getElementById("emp").removeEventListener("keypress");

But it throws an error:

Uncaught TypeError: Failed to execute 'removeEventListener' on 'EventTarget': 2 arguments required, but only 1 present.

How do I remove the event?

CodePudding user response:

The attribute on HTML tags operates like a function vs an event listener. In order to achieve what you're after you just need to edit or remove that attribute

if(condition)
    document.getElementById("emp").setAttribute("onkeypress", "");

if(condition)
    document.getElementById("emp").removeAttribute("onkeypress");

CodePudding user response:

Here is one way to do it:

<input type="text" id="emp" oninput="console.log(this.value)" >
<button onclick='document.querySelector("input").oninput=null'>remove event</button>

CodePudding user response:

Type and listener are required arguments for removeEventListener. A listener is removed from an event target based on its type and the EventListener function of the event handler to remove.

Thus, in the place of the listener, you should put a null like this below. Hopefully, it will work.

document.getElementById("emp").removeEventListener('onkeypress',null);

CodePudding user response:

You can make it easier. Instead to remove the event you can set return false if the condition true. In this example if the value length is longer then 3 chars the condition will toggle.

// const i = document.querySelector('input');

function myF(event) 
{
    const charCode = event.keyCode;
    const condition = event.target.value.length < 3 ? false : true;
  
    if (condition) {
      console.log('condition true');
      return false;
    }
  
    if ((charCode > 64 && charCode < 91) || 
        (charCode > 96 && charCode < 123) || 
        charCode == 8) {
      return true; }
    else {
      return false;
    }              
}
<input type="text" id="emp" onkeypress="return myF(event)" >

  • Related