Reputation: 4410
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
Reputation: 27012
.text()
overwrites the element's content, so you end up with what happened in the last iteration. Try .append()
instead:
$.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
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);
Upvotes: 2
Reputation: 2375
$.each(defaults, function(key, value) {
$('p').text( $('p').text() + key + ' : ' + value);
});
Upvotes: 1