blytung
blytung

Reputation: 405

Using foreach loop to print all results

I'm new to jQuery and I have got stuck on an each loop.

I'm trying to get the values from a variable with objects and when I print it using alert(), I get all the results.

But when I'm trying to print it to the HTML I only get the last result printed to the HTML instead of 3, in this case.

$.each(playlist, function(index, item) {
    alert(item.title);
    $('.playlist1').text(item.title);
}); 

Upvotes: 3

Views: 1313

Answers (3)

ahren
ahren

Reputation: 16959

Actually, you're not stuck on the .each() loop, you're stuck on .text().

.text() replaces the current text with new text, so you'll only ever see the last one in this case.

Maybe use .append().

You could also use .text() in this fashion:

$('.playlist1').text(function(index, text){
  return text + item.title;
});

Assuming .playlist1 is a ul or ol, you can append to it like this:

$('.playlist1').append('<li>'+item.title+'</li>');

Upvotes: 4

Travis J
Travis J

Reputation: 82297

Using alert can interrupt the execution of the script, consider using console.log()

console.log(item.title);

An each loop iterates much like a foreach, in this case i is the iterator, and item is the value

$.each(playlist, function (i, item) {

When you iterate, you are setting the text of every element with "class=playlist1" to item.title.

 $('.playlist1').text(item.title);
}); 

Although nothing is wrong syntactically, there is a logical error. Perhaps you could try this:

var fulltext = [];//initialize empty array
$.each(playlist, function (i, item) {
 fulltext.push(item.title);//iterate through playlist and collect titles
}); 
$('.playlist1').text(fulltext.join(" "));//join array with titles with a blank space
                                         //and put them in class playlist1

you could do this for list items:

var ul = document.createElement("ul");
$.each(playlist, function (i, item) {
 var thisLi = document.createElement("li");
 thisLi.innerHTML = item;
 ul.appendChild(thisLi);
}); 
$('.playlist1').append(ul);

Upvotes: 1

Andrew Cooper
Andrew Cooper

Reputation: 32586

You need to use the append function rather than text:

$('.playlist1').append(item.title); 

text() replaces the contents of the element with the new content. append() appends the new content to the existing contents of the element.

Update

To add each item as a list item do this:

$('.playlist1').append('<li>' + item.title + '</li>'); 

Upvotes: 2

Related Questions