Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

addeventlistener getting eaten by subsequent uses

This is must be some strange js thing I’m not aware of, but why will this code only log if the last input field changes? (Id 3) Since I am adding the eventListeners to all input fields, I’d expect outputs from all of them…

function constructInputs(ctx, id) {
    console.log(id);

    ctx.innerHTML += `<input type="text" id="${id}_textInput"></br>`;
    let textInput = document.getElementById(`${id}_textInput`);
    textInput.addEventListener("input", function (e) { 
        console.log(id);
    });
}

const ctx = document.getElementById("centerdiv");

constructInputs(ctx, '1');
constructInputs(ctx, '2');
constructInputs(ctx, '3');
<body>
    <div style="text-align: center;" id="centerdiv">
    </div>
    <script src="./main.js"></script>
</body>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Overwriting the innerHTML will effectively destroy all event listeners and recreate the elements. Use document.createElement and appendChild or append instead.

function constructInputs(ctx, id) {
  console.log(id);
  const input = document.createElement('input');
  input.id = `${id}_textInput`;
  ctx.append(input, document.createElement('br'));
  input.addEventListener("input", function(e) {
    console.log(id);
  });
}

const ctx = document.getElementById("centerdiv");

constructInputs(ctx, '1');
constructInputs(ctx, '2');
constructInputs(ctx, '3');
<div style="text-align: center;" id="centerdiv">
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading