0

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();
});
Community
  • 1
  • 1
Pierce McGeough
  • 3,016
  • 8
  • 43
  • 65

4 Answers4

2

Delegate the event to the static parent element

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

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
1

You need to use event delegation for dynamically added elements

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

DEMO

Satpal
  • 132,252
  • 13
  • 159
  • 168
0

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();
});
jingyinggong
  • 636
  • 5
  • 9
0

Please use delegate. Refer the updated fiddle.

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

$(document).delegate('.remove_highlight',"click", function(){
    $(this).closest('.form-group').remove();
});
Rupam Datta
  • 1,849
  • 1
  • 21
  • 36
  • Depending on jQuery version this may not be the best approach, see here: http://api.jquery.com/delegate/ "As of jQuery 1.7, .delegate() has been superseded by the .on() method. For earlier versions, however, it remains the most effective means to use event delegation. More information on event binding and delegation is in the .on() method." – Joshua Smickus Jan 03 '14 at 10:53