Saturday 30 November 2019

insertafter - jQuery dynamically added elements cannot be removed





I have been trying to work out a solution to this issue, and have come across many similar posts online,.. but none with solutions that worked for my particular instance.



I'm using jQuery it 'inserAfter' within a group of elements. I can add the groups easily,.. but, I also have a remove() function called when a delete link is clicked,.. but nothing happens to the newly added elements, even though I can delete the other groups without problems.



I'm using jQuery's on() for the click function.. but, that still doesn't work on the dynamically added elements.




To reproduce the issue, go to the jsfiddle link below,
Click the ADD GROUP button and see a yellow group added to the DOM.
Now, hover over the yellow group to show the delete button.
Click the delete button and, tada... nothin'



Here is an example:



http://jsfiddle.net/revive/5MFRm/




jQuery(function($) { 

$( "#tabs" ).tabs();
$("#group0").hide();
$('.group-content').hide(); // Hide all group-content elements

function clonePanel() {
var panel=$("#tabs #group0").clone(false),
lastpanel = $("#tabs .group").last().index(),
newid = 'group'+(lastpanel+1);


panel.attr('id',newid).addClass('newpanel');
panel.insertAfter($("#tabs .group").last()).show();
}

$(".add-group").on('click',function(){
clonePanel();
});

$(".delete-group").on('click',function(){

$(this).closest('.group').fadeOut('slow', function(){$(this).closest('.group').remove(); });
// alert('done');
});

$('#tabs').on('click', '.group-title-toggle',function(){ // Add class "hover" on dt when hover
$(this).closest('.group-title').toggleClass('active').next().slideToggle(); // Toggle dd when the respective dt is clicked
});

});


Answer



That is what you are looking for: In jQuery, how to attach events to dynamic html elements?.



And here is your code working properly.
http://jsfiddle.net/5MFRm/2/



Instead of $('.add-group').on('click', function() {})



use this notation




$('body').on('click', '.add-group', function() {})


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...