groseler groseler - 3 months ago 34
Javascript Question

Click to remove parent div

I'm struggling for something that seems pretty basic, though I'm not seeing what I am doing wrong.

I want that onClick a certain div is cloned till the maximum of 4 times. (So far so good), and I want to have a remove button that deletes one of the divs inserted.

And my problem is right there. I can't get the remove button to work.

JS

$(document).ready(function() {
var max_fields = 4; // maximum input boxes allowed
var wrapper = $("#addDriverContent div:first");
var add_button = $(".add_field_button"); // Add button ID
var x = 0

$(add_button).click(function(e) {
e.preventDefault();
// max input box allowed
if(x < max_fields) {
x++;
$(wrapper).clone().append('<a href="#" class="remove_field">Remove</a>').appendTo($('#clone_wrapper'));}
});

// user click on remove text
$(wrapper).on("click",".remove_field", function(e) {
e.preventDefault();
$(this).parent().sibling('#content').remove();
x--;
})

});


HTML

<div id="addDriverContent" style="display:none;">
<div id="content">
Contents
</div>
</div>

<button type="button" class="add_field_button" id="clone_button">ADD DRIVER</button>
<div id="clone_wrapper"></div>


Take a look at my fiddle.

(I've started with this example)

Answer

There are two problems with your javascript

  1. You are attaching the click event handler to wrong element. The element you are attaching to is not even visible on page and is never clicked.
  2. Your line where you try to remove the clicked content is wrong. $(this).parent().remove() is enough.

See Updated Fiddle

$(document).ready(function() {
    var max_fields = 4; //maximum input boxes allowed
    var wrapper = $("#addDriverContent div:first");
    var add_button = $(".add_field_button"); //Add button ID
    var x = 0

    $(add_button).click(function(e) {
        e.preventDefault();
        if (x < max_fields) { //max input box allowed
            x++;
            $(wrapper).clone().append('<a href="#" class="remove_field">Remove</a>').appendTo($('#clone_wrapper'));
        }
    });

    $(document).on("click", ".remove_field", function(e) { //user click on remove text
        e.preventDefault();
        $(this).parent().remove();
        x--;
    })
});
Comments