Pierce McGeough
Pierce McGeough

Reputation: 3086

Why does jquery not remove an appened div

I have fields in a form and allow the user to add or remove items. The first appended highlight will remove ok but any added ones will not remove.

I have tried the following and had no luck jQuery $(this).remove() not working after append

Here is a jsfiddle of the code below http://jsfiddle.net/3PzmH/3/

<!-- html -->
<div class="features"></div>

// js
var highlight = '<div class="form-group"><label for="highlight" class="col-sm-3 col-lg-2 control-label">Hightlight:</label><div class="col-sm-9 col-lg-3 controls"><input type="text" name="highlight_name[]" data-rule-required="true" class="form-control" value="Hightlight Name"></div><div class="col-sm-9 col-lg-7 controls"><textarea name="highlight_description[]" class="form-control" rows="3" placeholder="Description for highlight"></textarea><a href="" class="pull-right showhouse-text remove_highlight"><i class="fa fa-plus"></i> Remove Highlight</a></div></div>';
$('.features').append(highlight);

$('#add_highlight').click(function(){
    $('.features').append(highlight);
});

$('.remove_highlight').on("click", function(){
    $(this).closest('.form-group').remove();
});

Upvotes: 0

Views: 67

Answers (4)

Rupam Datta
Rupam Datta

Reputation: 1889

Please use delegate. Refer the updated fiddle.

http://jsfiddle.net/3PzmH/7/

$(document).delegate('.remove_highlight',"click", function(){
    $(this).closest('.form-group').remove();
});

Upvotes: 0

jingyinggong
jingyinggong

Reputation: 646

because dynamically added element dos not bind any function on it.

use the event delegation

$('.features').on('click', '.remove_highlight', function() {
    $(this).closest('.form-group').remove();
});

Upvotes: 0

adeneo
adeneo

Reputation: 318302

Delegate the event to the static parent element

$('.features').on("click", '.remove_highlight', function(){
    $(this).closest('.form-group').remove();
});

FIDDLE

Upvotes: 2

Satpal
Satpal

Reputation: 133423

You need to use event delegation for dynamically added elements

$('.features').on("click",'.remove_highlight', function(){
    $(this).closest('.form-group').remove();
});

DEMO

Upvotes: 1

Related Questions