ntgCleaner
ntgCleaner

Reputation: 5985

jQuery append overwriting last element

I am trying to dynamically create a list where I append a cloned div.

First, I have the div in html

<main>
    <div class="clone_me">
        ...
    </div>
</main>

in the jquery, I clone the div then remove it from the page. Then later, on keyup, I do some searching with an AJAX call and return 20 results. I can see all 20 results.

$(function(){
    var clone = $('.clone_me').clone();
    $('.clone_me').remove;

    $(document).on('keyup', 'input', function() {
        var variable = $(this).val();
        $.ajax({
            url: "link/to/script.php",
            type:"POST",
            dataType: "json",
            data {variable:variable},
            success: function(data){ 
                var json = JSON.parse(data);
                $.each(json.arrayVal, function() {
                    var value = this.value;
                    clone.find('.details').text(value);
                    $('main').append(clone);
                }
            }
        });
    });
});

Now, the ajax call returns 20 rows (I can read them all in console, so I know it's working [and yes, of course it's just dummy information, but I know it works]).

When I append the clone, for some reason it's overwriting the one before it, so Instead of ending up with 20 clones, I end up with a single clone with the last value from the AJAX call.

How do I get all 20 clones to be appended and show up?

Upvotes: 0

Views: 1176

Answers (1)

JC Hern&#225;ndez
JC Hern&#225;ndez

Reputation: 807

Lol you need to "clone" the clone var, like this:

$(function(){
    var clone = $('.clone_me').clone();
    $('.clone_me').remove();

    $(document).on('keyup', 'input', function() {
        var variable = $(this).val();
        $.ajax({
            url: "link/to/script.php",
            type:"POST",
            dataType: "json",
            data {variable:variable},
            success: function(data){ 
                var json = JSON.parse(data);
                $.each(json.arrayVal, function() {
                    var value = this.value;
                    var newclone = clone.clone().find('.details').text(value);
                    $('main').append(newclone );
                }
            }
        });
    });
});

Upvotes: 1

Related Questions