Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

put array element value in span jquery

var data = [{"id":"2015-07-003","cname":"John Smith ","caddress":"Tokyo,Japan","ccontact":"123"},{"id":"2015-07-003","cname":"James Harden","caddress":"Osaka Japan","ccontact":"345"}]



$.each(data, function(item, element) {
  alert(element.cname);
  $('#name').text(element.cname);
});


<span id='name'></span>

In above i want to put the names in the array inside the span but what is happening is only one name is shown the last one. Meaning the names is overriden how can i iterate the name so all can be shown

I want it to look like

John Smith
James Harden
like image 945
guradio Avatar asked Jul 06 '15 05:07

guradio


2 Answers

The problem is using .text() will override the previous value with new one, you need to keep appending the value to the previous one.

So one solution is to create an array of cname then use .join() to generate the desired output html and use .html() to set the content

var data = [{
  "id": "2015-07-003",
  "cname": "John Smith ",
  "caddress": "Tokyo,Japan",
  "ccontact": "123"
}, {
  "id": "2015-07-003",
  "cname": "James Harden",
  "caddress": "Osaka Japan",
  "ccontact": "345"
}]


$('#name').html($.map(data, function(item) {
  return item.cname
}).join('<br />'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span id='name'></span>
like image 152
Arun P Johny Avatar answered Sep 24 '22 00:09

Arun P Johny


use append()

  $('#name').append(element.cname+"<br>");

DEMO

like image 31
Balachandran Avatar answered Sep 26 '22 00:09

Balachandran