Sila Khatun Sila Khatun - 5 months ago 11
jQuery Question

jQuery remove div which added with jQuery

This is capture

I add some div with jQuery, Every div have a cancel button for remove the div.
But div remove button not working.
Here is my div remove code

$('.canceltag').click(function(){
$(this).parent().remove();
});


And here is my full jQuery code

$(document).ready(function(){
var BaseURL = $(".BaseURL").val();
var fPeople = $('.fPeople').val();
$('.fPeople').typeahead({
ajax: {
url: ""+ BaseURL +"json/tag",
method: 'post',
triggerLength: 1
},
onSelect: (function(item){
var aprid = item.value;
var aprname = item.text;
var nappr = " <i class='tagcover'>"+ aprname +" <b class='cursor_pointer text-danger canceltag'>X</b><input type='hidden' name='tag[]' value='"+ aprid +"'></i>";
$(".selectedname").append(nappr);

$('.fPeople').val('');
})
});

$('.canceltag').click(function(){
$(this).parent().remove();
});

});

Answer

Use event delegation to attach event to dynamically created element appended to document

// attach event to `.canceltag` parent element
$(".selectedname").on("click", ".canceltag", function() {
    $(this).parent().remove();
});