Reputation: 179
I'm trying to load products from json file using for loop. For every product I want to have a div (every item in a div). I have no problem with loading but somehow the first item data, looks like its being concatenate with the next item. I tried to go through net solutions and the closest I got is something to do with parent. (I'm still green at jQuery). The amount of divs for each item is working correctly.
if($.isArray(item.product_Shorts)){
$.each(item.product_Shorts, function(i, item){
$('#CasualItems').append("<div class='title'>");
$('.title').append(item.product_ID);
});
}
Currently I have two products, one with id 3 and another with 4. (for the sake of this I'm displaying ID instead of Title. Thanks.
Upvotes: 0
Views: 3945
Reputation: 6723
In the first loop, it appends the div and appends the product ID of 3 (to all 'title' classes). In the second pass, it appends a div and then adds the product ID of 4 (again to all 'title' classes, of which there are now 2).
Just do this instead:
$('#CasualItems').append("<div class='title'>").append(item.product_ID);
Upvotes: 1
Reputation: 4343
try this:
if($.isArray(item.product_Shorts)){
$.each(item.product_Shorts, function(i, item){
$('#CasualItems').append("<div class='title'>").html(item.product_ID);
});
}
Upvotes: 2
Reputation: 73896
Try this, using unique id
for each div
if($.isArray(item.product_Shorts)){
$.each(item.product_Shorts, function(i, item){
$('#CasualItems').append("<div id='title'" + (i + 1) + ">");
$('#title' + (i + 1)).append(item.product_ID);
});
}
Upvotes: 1
Reputation: 2053
It's because you are adding it to every .title div
. try doing it by id
or index.
$('.title').eq(i).append(item.product_ID);
Upvotes: 1