Event Listeners Firing Multiple Times -How to Implement?

michaelj9108429

08-12-2018

I have a form and I'm trying to track 3 selects in the form and 3 text fields, using DTM. I can't get it to work properly? I tried an event-based rule first with my test code and the selects work as designed until I click on a text field. First time I click on a text field, the code works fine but then anytime after that when I click on any element with a listener, the code runs proportionally. For example, If I change the value in the text field, that code will run twice. If I then change the select, that code will run 3 times etc. I have also tried this code in a page load rule and the selects work fine but the text fields don't work at all. I have no idea how to fix this issue? Any advice is appreciated.

var employmentStatusSelect = document.getElementById('mainForm:cont');

employmentStatusSelect.addEventListener('change',trackEmploymentStatusSelect);

  function trackEmploymentStatusSelect (){

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

    }

    employmentStatusSelect.removeEventListener('change', trackEmploymentStatusSelect);

};

var startCurrentJobInput = document.getElementById('mainForm:cont2');

startCurrentJobInput.addEventListener('blur', trackStartCurrentJobInput);

function trackStartCurrentJobInput(){

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

    }

    startCurrentJobInput.removeEventListener('blur', trackStartCurrentJobInput);

};

Accepted Solutions (0)

Answers (1)

Answers (1)

StewSchilling

MVP

10-12-2018

It seems pretty strange that you have DTM event rules that run JS code which adds/removes eventListeners.

When you create a DTM event-based rule, it is creating the listener for you. 

I think I would suggest creating DTM event rules

One triggered by the 'change' event  on  `#mainForm:cont`

Another triggered by the 'blur' event on `#mainForm:cont2`

BTW, I suspect that what you are presently seeing is that your DTM rule keeps adding event listeners.  This is compounded by the fact that your removeEventListener calls are failing.  So, yeah - 1st time, one function call. 2nd time, two function calls, etc.