1

I'm using BootStarp3 as the skeleton. I'm creating several elements dynamically (on button click), with the option to delete each created element with another button. The problem is that I'm only able to delete the first element, other created dynamically buttons don't seem to react, can't figure out what is wrong.

JSfiddle code here.

HTML:

<div id="reward-container">
    <div class="center-block col-lg-10 col-md-10 col-sm-12 text-left" id="">
           <div class="center-block col-centered bg-white review text-left"> 
            <div class="row">
                <div class="col-lg-6 col-md-5 col-sm-5">
                  <div class="form-group form-group-default">
                    <label>label</label>
                    <input type="text" class="form-control" placeholder="e.g">
                  </div>
                </div>
              </div>
        </div>

   <button class="btn btn-sm pull-right remove"><b>Remove</b></button>
    </div> 
</div>

<button class="btn btn-lg btn-info m-t-70 marg" id="add">add more</button>

JS:

$("#add").click(function(){
    var count = $("#reward-container").children();
    existingRewards = $("#reward-container").children();
       var newGift = $('<div class="center-block col-lg-10 col-md-10 col-sm-12 text-left marg" id='+count+'> \
                   <div class="center-block col-centered bg-white review text-left"> \
                    <div class="row"> \
                        <div class="col-lg-6 col-md-5 col-sm-5"> \
                          <div class="form-group form-group-default"> \
                            <label class="to-uppercase">label</label> \
                            <input type="text" class="form-control" placeholder="e.g"> \
                          </div> \
                        </div> \
                      </div> \
                </div> \
                <button class="btn btn-sm pull-right remove"><b>Remove</b></button> \
            </div>');
    $(newGift).appendTo("#reward-container");

});

//remove field

$(".remove").click(function(e){
    console.log("remove clicked");
    var father=e.target.parentElement.parentElement;
    existingRewards = $("#reward-container").children();
    if(existingRewards.length==1){
        console.log("one field remains");
    }else{
        $(father).remove();
    }
});
Alex
  • 1,982
  • 4
  • 37
  • 70

3 Answers3

6

That's because you need event delegation. Currently you're attaching the click handler to the .remove elements, but they are not there (you dinamically generate them). To catch the click on the new elements change the click handler into something like this:

$("#reward-container").on("click", ".remove", function (e) { ... });

You can also improve your function to use the closest method instead of navigating using parents:

$("#reward-container").on("click", ".remove", function(e){
    console.log("remove clicked");
    var $div = $(this).closest("div.center-block");
    existingRewards = $("#reward-container").children();
    if(existingRewards.length==1){
         console.log("one field remains");
    }else{
         $div.remove();
    }
});

JSFiddle

For more information, see my other similar answers:

Community
  • 1
  • 1
Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
  • Thanks for the answer. You, just to understand the point, for dynamically created elements I need to catch the click event because the created elements are "not registered" in the DOM at page creation? – Alex Oct 12 '15 at 13:31
  • 1
    @undroid Exactly! You got it. By using `$(".remove")` you *select* the **existing** elements on the page. Using my solution, you select the container and say: *when somebody clicks on this container, if the click is on the `.remove` element, **catch it!*** and it happens so. – Ionică Bizău Oct 12 '15 at 13:34
  • Amazing. Thanks again! – Alex Oct 12 '15 at 13:40
  • Another quick question. Upon button click, sometimes the click is registered on the parent container rather than on the button itself, what exactly is happening? In this example I catch the button click only when I click the text on the button. – Alex Oct 12 '15 at 14:01
  • 1
    @undroid Yeah, I fixed it. Use `closest` (see the edit). :) Glad I helped. – Ionică Bizău Oct 12 '15 at 14:08
0

While you binding click for remove, there is only one element with class remove. When you add another element, you should bind that click again.

$("#add").click(function(){
var count = $("#reward-container").children();
existingRewards = $("#reward-container").children();
   var newGift = $('<div class="center-block col-lg-10 col-md-10 col-sm-12 text-left marg" id='+count+'> \
               <div class="center-block col-centered bg-white review text-left"> \
                <div class="row"> \
                    <div class="col-lg-6 col-md-5 col-sm-5"> \
                      <div class="form-group form-group-default"> \
                        <label class="to-uppercase">label</label> \
                        <input type="text" class="form-control" placeholder="e.g"> \
                      </div> \
                    </div> \
                  </div> \
            </div> \
            <button class="btn btn-sm pull-right remove"><b>Remove</b></button> \
        </div>');
$(newGift).appendTo("#reward-container");
$(".remove").click(function(e){
    console.log("remove clicked");
    var father=e.target.parentElement.parentElement;
    existingRewards = $("#reward-container").children();
    if(existingRewards.length==1){
        console.log("one field remains");
    }else{
        $(father).remove();
    }
});

//remove field

$(".remove").click(function(e){
   console.log("remove clicked");
   var father=e.target.parentElement.parentElement;
   existingRewards = $("#reward-container").children();
   if(existingRewards.length==1){
      console.log("one field remains");
   }else{
      $(father).remove();
   }
});
brothers28
  • 1,196
  • 17
  • 23
0

As see in this post , you have to use

$('body').on('click', '.remove', function() {
    // do something
});

Instead of

$(".remove").click( function() {
    // do something
});
Community
  • 1
  • 1
Aroniaina
  • 1,252
  • 13
  • 31