jvk
jvk

Reputation: 2201

Unable to print JSON values using for loop

I have JSON values look like this

var results=[obj1,obj2,obj3];

and in

obj1['ádd':'usa','phone':121]
obj2['ádd':'cal','phone':143] 

and so. on.

Here I want to print all obj's address and pass to HTML id element.

I have done this way but it is print the only the first value but in console printing all values.

for (var i = 0; i < results.length; i++) {
  console.log(results[i].add);
  var jjj=(results[i].add);

  document.getElementById('target_2').innerHTML=jjj;
}

How to solve this problem?

Upvotes: 0

Views: 146

Answers (2)

xiaoyu2er
xiaoyu2er

Reputation: 166

var jjj = '';
for (var i = 0; i < results.length; i++) {
   console.log(results[i].add);
   jjj += results[i].add;
}
document.getElementById('target_2').innerHTML = jjj;

Upvotes: 2

Zack Tanner
Zack Tanner

Reputation: 2590

You are consistently replacing the innerHTML of target_2 rather than appending to it. You want to do something like this instead:

document.getElementById('target_2').innerHTML+=jjj;

Upvotes: 4

Related Questions