Reputation: 33998
I have the following code, when a checkbox is clicked it creates a div with some info. However in that div I added an anchor tag to remove the div itself.
However, I am not sure how to remove the div on the link click because the div is dynamically generated.
//Add selected job in the results div
function AddSelectedJob(id, display) {
//create a div for every selected job
$("[id$=ResultsDiv]").append('<div class="selectedjobs" id=' + id + '>' + display + '<a href="#">Remove selected job</a></div>');
}
Upvotes: 0
Views: 1198
Reputation: 1
I prefer using .parents() in this case.
And if possible, add a class to your anchor, then return false or use .preventDefault() to prevent anchor's default action.
//Add selected job in the results div
function AddSelectedJob(id, display) {
//create a div for every selected job
$("[id$=ResultsDiv]").append('<div class="selectedjobs" id=' + id + '>' + display + '<a class="removeSelectedJobs" href="#">Remove selected job</a></div>');
}
$('.selectedjobs .removeSelectedJobs').live('click', function() {
$(this).parents('.selectedjobs').remove();
return false;
});
Upvotes: 0
Reputation: 384
In this case divs are not usually created but are rather hidden instead by which you would a lot of hassle. You can create a div that has "display:none;" in CSS and then when the tickbox is checked you can use
$("[id$=ResultsDiv]").show();
and when it is unchecked,
$("[id$=ResultsDiv]").hide();
Upvotes: 0
Reputation: 36531
give your div
a class and use on
delegate event
try this
$("[id$=ResultsDiv]").append('<div class="selectedjobs" id=' + id + '>' + display + '<a href="#" class="removeJob">Remove selected job</a></div>');
$('[id$=ResultsDiv]').on('click','.removeJob',function(){
$(this).parent().remove();
})
OR
without using class
$('[id$=ResultsDiv]').on('click','.selectedjobs a',function(){
$(this).parent().remove();
})
note: delgating it to the closest static parent container is better than the document
itself
link to read more about on
events
Upvotes: 4
Reputation: 7380
Try live click...
$(".selectedjobs a").live("click", function(){
$(this).parent().remove();
});
Upvotes: 0
Reputation: 442
USE THIS CODE :-
//Add selected job in the results div
function AddSelectedJob(id, display) {
//create a div for every selected job
$("[id$=ResultsDiv]").append('<div class="selectedjobs" id=' + id + '>' + display + '<a href="javascript:;" onclick="removeSelectedJob(this)">Remove selected job</a></div>');
}
function removeSelectedJob(el){
$(el).parent().remove();
}
Upvotes: 2
Reputation: 6047
something like:
$("#ResultsDiv>div.selectedjobs a").click(function(){
$(this).parent().remove();
});
Upvotes: 0
Reputation: 32581
$(document).on('click','.selectedjobs a',function(){
$(this).parent().remove();
});
Upvotes: 4