Reputation: 3587
I have an array:
var bar = [];
I have a for loop going through the array:
for (var i = 0; i <= 3; i++) {
$(".left-lg").find(".name").html(bar[i].name);
}
I am trying to replace the content of the DIV.name with the content in the array, it works but only gives me the last one in the array. I read, on a click event with javascript the loop will be at the end, so that is why.
Any way how to correct this so it will go through the entire loop and not just give the last one?
Upvotes: 0
Views: 723
Reputation: 3491
Thats because everytime you call:
$(".left-lg").find(".name").html(bar[i].name);
you are overwriting your previous loops.
Set a variable equal to the values you want in an array, then pass that array to the element:
var allNames;
for (var i = 0; i <= 3; i++) {
allNames = allNames + bar[i].name);
}
$(".left-lg").find(".name").html(allNames);
Upvotes: 0
Reputation: 836
Try using append instead of html
$(".left-lg").find(".name").append(bar[i].name);
Upvotes: 0
Reputation: 262949
That's because you're always setting the HTML content of all the elements matching .name
. Try using the index
argument supplied to each() instead:
$(".left-lg .name").each(function(index) {
$(this).html(bar[index].name);
});
Upvotes: 1