5
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
0

4 Answers 4

9

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>

Sign up to request clarification or add additional context in comments.

5 Comments

Is there a way to make it more flexible i mean i have other span i want to make like this.
@Pekka there could be if you can explain your requirement - if possible edit this fiddle to recreate your problem
jsfiddle.net/95g4b32k/3 then i want to put the value on each span that i added address for span with id address contact for span with id contact
@Pekka in that case using a each loop will be better
Yes like my code my only problem is how to put multiple values inside one span
3

use append()

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

DEMO

1 Comment

that wont be multi line though
1
var str = '';
$.each(data, function (item, element) {
    str += element.cname + '<br />';
});
$('#name').html(str);

Hope this helps.

Comments

1
//Declare a variable
var data=""

$.each(data, function(item, element) {
//Append element to data variable.

  alert(element.cname);
  data+=element.cname;
});

//Append the entire data to the span at the end.
$('#name').append(data);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.