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

216
Vistas
How do I stop JavaScript element clearing everything on click

The first delete produced works fine when clicked on "add more" but del element produced after that deletes everything present on the page. Can someone please help me, maybe something is wrong with ele, I don't have much experience with JS

Steps to reproduce :

  1. Click on add more and then the next add more which got created on click the previous add more.

  2. click on the last del

  3. It deletes everything rather than deleting that very DIV

$(function() {
  $(".btn-copy").on('click', function() {
    var ele = $(this).closest('.example-2').clone(true);
    ele.find('input').val('')
    if (ele.find('button').length<2) {
      let btn = document.createElement("button");
      btn.innerHTML = "Delete";
      btn.onclick = (e) => {
        e.preventDefault()
        ele.remove()
      }
      ele[0].appendChild(btn);
    }
    $(this).closest('.example-2').after(ele);
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
  <div class="col-lg-12">
    <div class="card">
      <div class="card-header">
        <h5 class="card-title">Add Class</h5>
      </div>
      <div class="card-body">
        <form action="#">
          <div class="example-2 form-group row">
            <!--<label class="col-form-label col-md-2">Input Addons</label>-->
            <div class="col-xs-2">
              <div class="input-group">
                <div class="input-group-prepend">
                  <span class="input-group-text">Class Name</span>
                </div>
                <input class="form-control" type="text">
                <div class="input-group-append">
                  <button class="btn-copy btn btn-primary" type="button">Add More</button>
                </div>
              </div>
            </div>
          </div>
          <div class="form-group row">
            <div class="col-xs-2">
              <button class="btn btn-primary" type="button">Submit</button>
            </div>
          </div>


        </form>
      </div>
    </div>
  </div>
</div>

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

0

The problem was in the use of .clone()

You where cloning the latest cloned element which forced you to create an if statement to prevent creating more than one delete button. But that also did not allow you to execute what was inside the if statement after a certain number of nodes cloned.

You also could not use the btn variable outside that if statement.

The solution is to clone always the first example-2element so we can jump the use of the if statement and allow the btn variable to be used freely.

I added an extra div #wrapper to use find('div').first() so the same example-2 element can be copied every time.

Snippet

$(function() {
  $(".btn-copy").on('click', function() {
    
    var ele = $('#wrapper').find('div').first().clone(true);
    ele.find('input').val('');
    
    let btn = document.createElement("button");
    btn.innerHTML = "Delete";
    ele[0].appendChild(btn);

    btn.onclick = (e) => { ele.remove() };
    $(this).closest('.example-2').after(ele);
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="wrapper">
  <div class="example-2 form-group row" style="margin-top:15px">
    <div class="col-xs-2">
      <div class="input-group">
        <div class="input-group-prepend">
          <span class="input-group-text">Class Name</span>
        </div>
        <input class="form-control" type="text">
        <div class="input-group-append">
          <button class="btn-copy btn btn-primary" type="button">Add More</button>
        </div>
      </div>
    </div>
  </div>
  <div class="form-group row">
    <div class="col-xs-2">
      <button class="btn btn-primary" type="button" style="margin-top:30px">Submit</button>
    </div>
  </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