Search code examples
jqueryclone

jquery clone function nested delete option


My demo, is really clear, when I clone my element I clone and delete the divs however, the :last element (li) should't been removed. what I'm missing?

is something to do with this!:

$(document).on("click", 'li.delete',function () {
            $(this).closest(".outerDiv").remove();
    if ($(this).is(".outerDiv:last")){
            return false;
    }

DEMO: http://jsfiddle.net/XeELs/86/

JQUERY var cloneCount = 0; $("#add-address").click(function() {

    $("#to-add-address").clone()
        .attr("id", "to-add-address_Clone" + cloneCount)
        .insertAfter("#to-add-address");
    $("#clone", "#to-add-address_Clone" + cloneCount)
        .attr("id", "clone_Clone" + cloneCount);
    cloneCount++;
});

$(document).on("click", '.options li a',function () {
            $(this).closest(".options").find('li a').removeClass('selected');
            $(this).addClass('selected');

        });
$(document).on("click", 'li.delete',function () {
            $(this).closest(".outerDiv").remove();
    if ($(this).is(".outerDiv:last")){
            return false;
    }

});


Solution

  • try this code

    var cloneCount = 0;
    $("#add-address").click(function() {
    
        $("#to-add-address").clone()
            .attr("id", "to-add-address_Clone" + cloneCount)
            .insertAfter("#to-add-address").addClass('cloned');  //add a new class cloned to the cloned outerDivs
        $("#clone", "#to-add-address_Clone" + cloneCount)
            .attr("id", "clone_Clone" + cloneCount);
        cloneCount++;
    });
    
    $(document).on("click", '.options li a',function () {
                $(this).closest(".options").find('li a').removeClass('selected');
                $(this).addClass('selected');
    
            });
    $(document).on("click", 'li.delete',function () {
                $(this).closest(".outerDiv").filter('.cloned').remove(); // and delete only the cloned ones
        if ($(this).is(".outerDiv:last")){
                return false;
        }   
    });