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)
There are two problems with your javascript
click event handler to wrong element. The element you are attaching to is not even visible on page and is never clicked.$(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--;
})
});
Change your event listener to the following:
$("#clone_wrapper").on("click",".remove_field", function(e) {
e.preventDefault(); $(this).parent().remove(); x--;
});
Working Example.
I've made two changes:
$(wrapper) to $("#clone_wrapper"). The .remove_field links are added to the wrapper clone, not the wrapper itself (from appendTo($('#clone_wrapper')))$(this).parent().sibling('#content') to $(this).parent(). The parent is the #content — you don't want to remove its sibling.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With