Rossitten Rossitten - 5 months ago 9
jQuery Question

Jquery add and remove several divs with one click

here is the code:

$('.add').click(function() {

var description = $('#description').val();
$(".append_data").append('<div class="row" style="background: #e6e6e6; color: #666; border-bottom: solid 1px #fff;"><div class="col-md-3"><input type="text" name="1"></div><div class="col-md-5"><input type="text" name="2"></div><div class="col-md-2"><input type="text" name="3"></div><div class="col-md-2"><input type="text" name="4"></div></div><div class="remove">Remove</div>');

});

$('.append_data').on('click', '.remove', function(e) {
//alert('boom');
e.preventDefault();
$(this).closest('.row').remove();
return false;
});


Here is the code's Fiddle:
https://jsfiddle.net/L7su5ke7/

It adds several divs , all right. But how I can delete those with one click - alas! I have not figured out ((
I have tried "closest" and "parents" both with no luck

Answer

What I did is that I enclosed that html code that you dynamically add with another <div>

$('.add').click(function() {

var description = $('#description').val();
$(".append_data").append('<div><div class="row" style="background: #e6e6e6; color: #666; border-bottom: solid 1px #fff;"><div class="col-md-3"><input type="text" name="1"></div><div class="col-md-5"><input type="text" name="2"></div><div class="col-md-2"><input type="text" name="3"></div><div class="col-md-2"><input type="text" name="4"></div></div><div class="remove">Remove</div></div>');

});

$('.append_data').on('click', '.remove', function(e) {
  e.preventDefault();
  $(this).parent().remove();
});

Then just removed the parent when the remove button is clicked!

Link: jsfiddle link

Comments