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?
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>
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");
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)" >