Search code examples
javascriptaddeventlistener

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

  • 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>