jQuery each array index append to div

10,433

You are adding the items to the array, which makes sense if you want to keep a list of added items, but then you are looping through the array when adding items to the list, which will make it add all items to the items already existing there.

You can just add the last item:

array.push($(this).siblings('p').text());
$("#cart ul").append("<li>" + array[array.length - 1] + "</li>");

or you can clear the list before adding the items:

array.push($(this).siblings('p').text());
$("#cart ul").empty();
$.each(array, function(index, value) {
  $("#cart ul").append("<li>" + value + "</li>");
});
Share:
10,433
user2201765
Author by

user2201765

Updated on June 04, 2022

Comments

  • user2201765
    user2201765 almost 2 years

    I'm trying to append the values of array I've made into another div but when I append the array value its appending all the values of the array not just the one I've added(by click), any suggestions would be great, thanks in advance!

    HTML

    <div id="products">
        <ul>
            <li><p>Lorem 1</p><button class="target">Add</button></li>
            <li><p>Lorem 2</p><button class="target">Add</button></li>
        </ul>
    </div>
    <div id="cart">
        <ul>
    
        </ul>
    </div>
    

    jQuery

    $(document).ready(function(){
    
        var array = Array();
    
        $(".target").click(function() {
    
            array.push($(this).siblings('p').text());
    
            $.each(array, function(index, value) {
    
                $("#cart ul").append("<li>"+value+"</li>");
            });
    
    
        });
    });
    

    When I click Add on say the first button its displays

    Lorem 1

    but when I then click the add on the second button it displays

    Lorem 1 Lorem 1 Lorem 2

  • user2201765
    user2201765 about 11 years
    That makes sense but how would I get the value of my array then?
  • user2201765
    user2201765 about 11 years
    Thanks @Guffa that makes sense, the [array.length - 1] is what I needed, thanks for you think and the well written explanation! Cheers
  • RestingRobot
    RestingRobot about 11 years
    Do you really want to re-add all of the items that are already in the list? If he is just adding one item per click, this function removes and adds the same list subset over and over.
  • RestingRobot
    RestingRobot about 11 years
    Well, I mean redundant code is redundant no matter how many items are in the list. What if each element requires an AJAX request? There are many cases that could make this operation really expensive. It doesn't appear in this example, but for the sake of everyone else using this as a reference, it would be best not to be inefficient.
  • Roko C. Buljan
    Roko C. Buljan about 11 years
    @Jlange you're perfectly right. Edited to reflect your comment