views:

82

answers:

3

Hello, I have a simple question concerning Javascript. I am trying to print in a loop some values to div container. The problem is that instead printing the value several times in a loop, each time it is overwritten and as a result I get only one value. See the code below:

for (i=0; i<json.Locations.length; i++) {
var location = json.Locations[i];

var content =     document.getElementById('eventsnearby');                                                    
var html = location.name;
content.innerHTML = html;



}

Any ideas welcomed. Thanks.

+4  A: 

Append, don't assign.

content.innerHTML += html;

Better yet, use standard DOM.

var content = document.getElementById('eventsnearby');                                                        
for (var i = 0; i < json.Locations.length; i++) {
    var text = json.Locations[i].name;
    var node = document.createTextNode(text);
    content.appendChild(node);
}
David Dorward
It works. Thanks a lot.
Vafello
+1  A: 

You only get one value because you're setting the innerHTML property during each loop iteration instead of appending to it. Try using content.innerHTML += html;.

John Topley
+1  A: 
for (i=0; i<json.Locations.length; i++) {
var location = json.Locations[i];

var content = document.getElementById('eventsnearby');                                                    
var html = location.name;
content.innerHTML += html;
}
antyrat