MJ
asked on
Why Does Input Event Listener Run Multiple Times Depending on How Many Times I've Changed the Input?
I have the following code which I'm trying to attach an event handler to a text input. It works but each time I go back to this input field it adds an extra iteration so the second time I change the input the below code runs twice (I'll get 4 console.logs from single change). Each time I change the value the code runs that many times. So for example, if I change the value of the input text for the 5th time then the code will run 5 times in a row (I'll get 10 console.logs for the single change) as if each time it is attaching an additional event listener to the input. How do I fix this?
var startCurrentJobInput = document.getElementById('mainForm:cont_appRequest_customers__0_records_ichabod_fields__0_columns_start_job:decoin:appRequest_customers__0_records_ichabod_fields__0_columns_start_job');
startCurrentJobInput.addEventListener('blur',(event) => {
var scjVal = event.target.value;
console.log(" event.target.value ==> " + event.target.value);
if(scjVal != ""){
console.log("startCurrentJobInput ==> " + event.target.value);
} else {
console.log("startCurrentJobInput will not report");
}
});
Thanks!
Add a flag property the element so you only add event listeners to an element once by checking for the flag before doing so. Alternatively, move that initialization to a different place in your code, so it doesn't get called repeatedly.
ASKER
Hi David, Could you please show me?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thank you both!
You're welcome, glad to help.