MaxPower
MaxPower

Reputation: 367

$.each is only iterating through the last item in my array...Why is this happening?

I am trying to take an array from my DB, then target specific items in that array, put it into some HTML and have it render in the browser. In my code, the alert(v.displayName) will iterate through all the 'displayName' in my collection. However, when i put it into html elements, it only prints out the last item in my array. If I put return false $('.commentsForTheWin') then it will only print out the first item in my array.

$(function() {
    $('.commentsInit').click(function() {
        var uniCommID = $(this).attr("value");
        $.ajax({
            type: "GET",
            url: "/api/comments"
        }).success(function(users) {
            $.each(users, function(i, v) {
                alert(v.displayName);
                var b = '<div class="red">' +
                    '<div>' +
                    '<span>' +
                    i + " : " + v.username +
                    '</span>' +
                    '<span>' +
                    " hello" +
                    '</span>' +
                    '<span>' +
                    "45 pts" +
                    '</span>' +
                    '</div>' +
                    '</div>';
                $('.commentsForTheWin').html(b);
            });
            $('.hideOnLoad:contains(' + uniCommID + ')').toggle("slow");
        })
    })
});

I am guessing its not liking that I am putting it in .html? However .text doesn't change it either. Any help appreciated!

Upvotes: 1

Views: 78

Answers (3)

pmn
pmn

Reputation: 2247

Use .append() instead of .html(), because by .html() in every iterate you overwrite the existing content in commentsForTheWin element.

Upvotes: 0

Jai
Jai

Reputation: 74738

use append() instead:

 $('.commentsForTheWin').append(b);

.html() overwrites everything within the selector element.

Better way to create your html in loop and put them inside when you get all:

var b='';
$.each(users, function(i, v) {
  b += '<div class="red">' +
    '<div>' +
    '<span>' +
    i + " : " + v.username +
    '</span>' +
    '<span>' +
    " hello" +
    '</span>' +
    '<span>' +
    "45 pts" +
    '</span>' +
    '</div>' +
    '</div>';
});
$('.commentsForTheWin').html(b);

Upvotes: 2

Satpal
Satpal

Reputation: 133403

The problem arises as .html() overwrites the existing content, thus you are getting content added by last iteration.

You need to to use .append() instead of .html() and empty() to remove existing content.

//Remove the content before iteration
$('.commentsForTheWin').empty();

$.each(users, function (i, v) {
    ...
    //append new content
    $('.commentsForTheWin').append(b);
});

Another approach is to create a complete HTML string then use .html()

var htmlContent = '';
$.each(users, function (i, v) {
    ...
    //append new content
    htmlContent += b;

});
$('.commentsForTheWin').html(b);

Upvotes: 5

Related Questions