JQuery Can't delete section after cloning
I am creating a button Add Section
for the cloning section .clone
working fine ...
The main point that I cannot continue Remove Section
is this button is not working. i want to click on Remove Section
, it will delete the section itself.
Html
<div style="margin-bottom:25px;">
<button class="add_section btn btn-primary" type="button"><i class="fa fa-plus"></i> Add Section</button>
</div>
<div class="panel clone" id="primary">
<div class="panel-heading">
<span class="panel-title" id="secPanel">Section #Primary</span>
<button style="float:right;" class="rem_section btn btn-primary" type="button"><i class="fa fa-remove"></i>Remove Section</button>
</div>
<div class="panel-body admin-form">
<div class="form-horizontal">
<div class="form-group">
<label class="col-lg-2 control-label">Description</label>
<div class="col-lg-8">
<input id="secTitle" name="txt_sectitle[]" value="" type="text" class="form-control">
</div>
</div>
</div>
</div>
</div>
</div>
<div id="pastclone"></div>
Js
jQuery(document).ready(function() {
// Init jQuery Add Section
$('.add_section').on('click', function(){
var num = $('div.clone').length,
clone = $('#primary').clone().attr('id', num);
clone.find('#secPanel').html('Section #' + num);
clone.find('[type=text]').val('');
clone.find('.rem_section').attr('class', 'rem_section'+num+' btn btn-primary');
clone.insertBefore("#pastclone");
return false;
});
// Init jQuery Remove Section
$(".clone").on("click", ".rem_section", function(){
$(this).parent(".clone").remove();
return false;
});
});
My JSFIDDLE
source to share
Unable to delete because you are changing the attribute class name of each element with the value increment. No extra value needed since you are attaching the click event to class
.
This
clone.find('.rem_section').attr('class', 'rem_section'+num+' btn btn-primary');
it should be
clone.find('.rem_section').attr('class', 'rem_section btn btn-primary');
And the remove element will only find the straight line only parent
, it would be better to use closest
like this:
$(document).on("click", ".rem_section", function(){
$(this).closest(".clone").remove();
return false;
});
source to share
The clone element is also dynamically instantiated, so you need to bind the handler to the predecessor element of the dynamic element that is present when the event is registered
$(document).on("click", ".clone .rem_section", function(){
$(this).closest(".clone").remove();
return false;
});
Also when you clone the class is rem_section
not added.
clone.find('.rem_section').attr('class', 'rem_section rem_section'+num+' btn btn-primary');
Demo: Fiddle
source to share