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();
}
});