Search code examples
jqueryappenddetach

JQuery Append then Remove


Fiddle: http://jsfiddle.net/YbfZG/4/ For some reason the toggleDiv/removeDiv functions aren't working (I haven't used jsfiddle much), but hopefully this will give you a better idea of what I'm trying to accomplish.

I've got a page where users can add items (divs) dynamically by making a selection from a dropdown. This is accomplished via .append(). They can also remove an item (.remove()) and potentially re-add it. Each div contains a hide/show area triggered by clicking on a link.

The first time a div is added to the page, the hide/show area works fine. If the same div is removed and then re-added, the hide/show no longer works. I believe this is because the div isn't being completely removed from the DOM, so the hide/show function - which operates based on ids - can't find the correct div to work on.

I've tried modifying my remove function to be $(this).empty().remove(); but that didn't work. I also tried using detach as well, but there was no change in the functionality. I did some reading and I potentially need to be using .on(), but I'm not sure how to structure that.

ETA: Append & toggle code and changed div name to not be solely numeric (typo on my part).


Solution

  • It will be easier if you change your markup to:

    <div id="8" class="wrapper">
        <div>
        <a title="Remove" class="remove" href="#">Remove</a>
        </div>
    </div>
    

    (basically i added a "wrapper" class to the main div and a "remove" class to the remove link)

    So you'll get rid of the onclick attribute and use a simple function instead:

    $('body').on('click','a.remove',function(){
        $(this).closest('div.wrapper').remove();
    });​
    

    Demo


    Given your full code, here's how to make it work (demo) :

    $(function() {
    
        $('.elements').on('click', '.remove', function() {
            $(this).closest('div[id^=div]').remove();
        });
    
        $('.elements').on('click', '.open-close', function() {
            var hideShowN = $(this).closest('div[id^=div]').attr('id').replace(/\D/g,'');
            $('#hide_show_'+hideShowN).toggle();
        });
    
        $('.add').on('click', function() {
            $('.elements').append('<div id="div_8">Element<a class="open-close" href="#" title="Open/Close">Open/Close</a><div id="hide_show_8" style="display: none;">Stuff</div><a class="remove" href="#" title="Remove">Remove</a></div>');
        });
    
    });​