Search code examples
jqueryajaxjsoncloneeach

jquery cloning within a loop?


I have a question about cloning within a loop, two problems actually and im just trying to find the best way around it, below is my code.

$.each(data.customers,function(key, value){
    $('.customer').find('label').eq(0).text( value.name );
    $('.customer').eq(0).clone().appendTo('#customers');
});

The data.customers is in json format so I cannot do a .length on it. My problem is the jquery will always append a clone element on the end of #customers regardless. I need to only append if their is another one in the json collection. The only way I can think of doing it is returning the count of the array back as json and checking that the key is equal to it which seems absurd. Whats the best way to clone elements when your dealing with a loop?

Can anyone help.


Solution

  • You could do this:

    First, create a specific "cloning template" for customers in your HTML, make that invisible via CSS (.template {display: none;}).

    Then, in your loop:

    $.each(data.customers, function (key, value) {
        var $newCustomer = $('#customers .customer.template').clone();
    
        $newCustomer.removeClass("template").find('label:first').text( value.name );
        $('#customers').append( $newCustomer );
    });