Home > database >  Is there a way of deleting this div with a button with jQuery?
Is there a way of deleting this div with a button with jQuery?

Time:04-23

I'm working on some jQuery on my website. The logic to create a new container with new inputs is already made, but the delete button doesn't work. Any hints or paths to go?

var i = 0;
$("#addAula").click(function() {

  i  ;

  $("#newAula").append('<div  id="containerAula'   [i]   '"> <div > <label >Título</label> <input type="text" id="titulo_aula'   [i]   '"  required> </div> <div > <label >Video ID</label> <input type="text" id="video_id'   [i]   '" required> </div> <div > <button id="removeAula'   [i]   '"> X </button> </div> <p ></div>');

});

$("#removeAula"   i).click(function() {
  $("#containerAula"   i).remove(); //where i'm trying to reach the delete action
});
<div id="newAula">

  <div  id="containerAula0">
    <div >
      <label >Título</label>
      <input type="text" name="titulo"  required>
    </div>
    <div >
      <label >Video ID</label>
      <input type="text" name="video_id"  required>
    </div>
    <div >
      <button id="removeAula0"  type="button">
                        X
                        </button>
    </div>
    <p >
    </p>
  </div>
</div>
<button id="addAula"  type="button">
                      Aula
                    </button>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

IMG: enter image description here

Sorry for any rookie mistake, thanks for your time

CodePudding user response:

The delete listener is using the global variable i, which gets incremented every time you add another DIV, not the value at the time the handler was created.

You need to use a local variable that's saved in the closure.

var i = 0;
$("#addAula").click(function() {

  i  ;

  $("#newAula").append('<div  id="containerAula'   [i]   '"> <div > <label >Título</label> <input type="text" id="titulo_aula'   [i]   '"  required> </div> <div > <label >Video ID</label> <input type="text" id="video_id'   [i]   '" required> </div> <div > <button id="removeAula'   [i]   '"> X </button> </div> <p ></div>');

  let cur = i;
  $("#removeAula"   i).click(function() {
    $("#containerAula"   cur).remove();
  });

});

CodePudding user response:

I think you should try something like this

<script>
   $(".removeAula").click(function(){
       $(this).parent('.containerAula').remove();
   });
</script>

You need to change your html by adding a class into every remove button (removeAula for example), and to every container (containerAula), select every remove button and add an event listener to it, inside that listener you just look for the parent of the clicked button and remove it.

I think it should work.

  • Related