Avatar of MJ
MJ
Flag for United States of America asked on

Prevent "onchange" Event Conflict in JavaScript?

I have the below test javascript code which works:
var EmploymentStatusSelect = document.getElementById('mainForm:cont_appRequest_customers__0_employmentStatus:decoin:appRequest_customers__0_employmentStatus');
EmploymentStatusSelect.onchange = (event) => {
    var esSelVal = event.target.value;
    console.log(" event.target.value ==> " + event.target.value);
    if(esSelVal != ""){
        console.log("EmploymentStatusSelect ==> " + event.target.value);  
    } else {
       console.log("EmploymentStatusSelect will not report");
    }
}

Open in new window

The issue is it prevents the form on the page from functioning properly. There is existing logic on the web app for the onchange event in the form so when certain selections are made, the form dynamically displays other questions. When I introduce my code (above) , the existing dynamic field display breaks. Is there a way to rectify this in my code? I am injecting code via a tag management system so I can't touch the code on the page, I can only change my injected code. Is there a way to fix my code so it won't impact the other onchange logic?

Thanks!
Web DevelopmentJavaScript

Avatar of undefined
Last Comment
MJ

8/22/2022 - Mon
David S.

It seems that you're overwriting the existing event handler. You need to add the new one via addEventListener() instead.
MJ

ASKER
Any idea how that would work based on the sample code?
ASKER CERTIFIED SOLUTION
David S.

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
MJ

ASKER
I also had luck with:
var employmentStatusSelect = document.getElementById('mainForm:cont_appRequest_customers__0_employmentStatus:decoin:appRequest_customers__0_employmentStatus');

employmentStatusSelect.addEventListener('change', function() {
 // alert(this.value);
 // var tv = this.value;
  console.log("________________1st select:: this.value holds: " + this.value);
}, false);

Open in new window

All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
MJ

ASKER
Thank you David!