Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

147
Vistas
eventlistener not working for dynamically created element

I have a simple section in which users can add input fields dynamically and users should be able to remove added input fields by clicking the delete button. am using vanilla js

here is a live demo : demo live codepen

HTML

<div id="domains-wrapper">
    <div class="input-group">
        <input name="domains" type="text" class="form-control domain-url" placeholder="Type valid url" value="" required="">
        <div class="valid-feedback">Looks good!</div>
        <button id="default-delete" style="display: none;" class="default-delete delete-input-el domain-btn btn-sm border border-1" type="button">
        </button>
        <button id="default-add" class="add-input-el added-input plus-button btn-sm border border-1 add_form_field" type="button">
            <span class="add-icon">+
            </span>
        </button>
    </div>
</div>

Js

var max_fields = 10;
var wrapper = document.getElementById("domains-wrapper");
var add_button = document.getElementById("default-add");

var x = 1;
add_button.addEventListener('click', function(e) {
    e.preventDefault();
    if (x < max_fields) {
        x++;
        $(wrapper).append('<div><input id="delete" type="text" name="mytext[]"/><a href="#" class="delete">Delete</a></div>'); //add input box
    } else {
        alert('You Reached the limits')
    }
})

var deleteBtn = document.querySelectorAll(".delete");

deleteBtn.forEach(function(e) {
    e.addEventListener('click', function() {
        console.log('PL')
      this.parentNode.remove(); //remove the whole div containing input and delete button
    })
});

Problem, Now when I click the delete button nothing is happening,

Any idea what am I missing here?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

your are not recovering the .delete to add listener after the click on more button

so delete field don't have listener

I can propose you to add the listener after the field append to solve your situation

    var max_fields = 10;
    var wrapper = document.getElementById("domains-wrapper");
    var add_button = document.getElementById("default-add");

    var x = 1;
    add_button.addEventListener('click', function(e) {
        e.preventDefault();
        if (x < max_fields) {
            x++;
            var deleteField = document.createElement('div');
            deleteField.insertAdjacentHTML('beforeend', '<input id="delete" type="text" name="mytext[]"/>');
            var a = document.createElement('a');
            a.href= '#';
            a.innerText = 'Delete';
            a.classList.add('delete');
            deleteField.append(a);
            wrapper.appendChild(deleteField); //add input box
              a.addEventListener('click', function() {
              var target = e.target || e.srcElement;
              console.log('PL')
              deleteField.remove();
           })
        } else {
            alert('You Reached the limits')
        }
    })
    <div id="domains-wrapper">
        <div class="input-group">
            <input name="domains" type="text" class="form-control domain-url" placeholder="Type valid url" value="" required="">
            <div class="valid-feedback">Looks good!</div>
            <button id="default-delete" style="display: none;" class="default-delete delete-input-el domain-btn btn-sm border border-1" type="button">
            </button>
            <button id="default-add" class="add-input-el added-input plus-button btn-sm border border-1 add_form_field" type="button">
                <span class="add-icon">+
                </span>
            </button>
        </div>
    </div>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda