Mdd
Mdd

Reputation: 4410

How to write the key/value pairs of an object to a page

I am trying to write the key/value pair's in an object to the page using jquery's .each() function. I can only get it to write out the last key/value pair however.

Here is fiddle and the code:

http://jsfiddle.net/Nirvanachain/2RsN9/

JS:

var defaults = {
 validate: false, 
 limit: 5, 
 name: "foo"   
};

$.each(defaults, function(key, value) {
  $('p').text(key + ' : ' + value);
});

HTML:

<p></p>

Upvotes: 1

Views: 112

Answers (3)

Jason P
Jason P

Reputation: 27012

.text() overwrites the element's content, so you end up with what happened in the last iteration. Try .append() instead:

http://jsfiddle.net/ZjwWn/

$.each(defaults, function(key, value) {
    $('p').append(key + ' : ' + value + '<br/>');
});

Edit - Ricardo's comment is correct. For best performance, modify the DOM as few times as possible. In this case, you should create a variable to append the text to, then append that to the DOM once.

Upvotes: 4

codingrose
codingrose

Reputation: 15699

.text() is overwriting.

You just need to save values in a variable OR append it.

Write this:

var defaults = {
    validate: false,
    limit: 5,
    name: "foo"
};
var txt = "";
$.each(defaults, function (key, value) {
    txt += key + ' : ' + value + " ";
});
$('p').text(txt);

Updated fiddle here.

Upvotes: 2

Ankit Tyagi
Ankit Tyagi

Reputation: 2375

$.each(defaults, function(key, value) {
    $('p').text( $('p').text() + key + ' : ' + value);
});

Upvotes: 1

Related Questions