blueintegral
blueintegral

Reputation: 1271

Only seeing results from last .each() iteration in jQuery

I'm trying to iterate through some stuff in a JSON file and I'm having trouble getting the each() to do what I want. Here's what I have:

$.each(response.data.items, function(i,data)
{
var id=data.id; 
var results="<div><iframe width='320' height = '190' src='http://www.example.com/"+id+"' frameborder='0' type='text/html'></iframe></div>";

$("#resultsOut").html(results);
});

Right now, the only HTML that is being output is

<div><iframe width='320' height = '190' src='http://www.example.com/"+id+"' frameborder='0' type='text/html'></iframe></div>

where id is the last id that occurs in the JSON. How do I change this so that instead I see that HTML block once for every id that occurs?

Upvotes: 0

Views: 130

Answers (3)

davecoulter
davecoulter

Reputation: 1826

You are only seeing the last id because you are overwriting the previous HTML with every iteration. Try using .append():

$.each(response.data.items, function(i,data)
{
var id=data.id; 
var results="<div><iframe width='320' height = '190' src='http://www.example.com/"+id+"' frameborder='0' type='text/html'></iframe></div>";

$("#resultsOut").append(results);
});

Upvotes: 0

FishBasketGordo
FishBasketGordo

Reputation: 23142

You're overwriting the inner HTML of $("#resultsOut") every time. Do something like this:

$.each(response.data.items, function(i,data)
{
    var id=data.id; 
    var results="<div><iframe width='320' height = '190' src='http://www.example.com/"+id+"'      frameborder='0' type='text/html'></iframe></div>";

    $("#resultsOut").append($(results));
});

Upvotes: 1

Amber
Amber

Reputation: 527298

You probably need to

$(results).appendTo("#resultsOut");

instead of

$("#resultsOut").html(results)

because .html() replaces the contents of the selected element with the new HTML, rather than adding to it.

Upvotes: 1

Related Questions