Reputation: 139
How would I output this data using Jquery.each() to loop over the following array using Jquery?
var data = [
{
value: 36,
color:"#89228f",
legend:"My title"
},
{
value: 12,
color:"#89288f",
legend:"This title"
}
]
I would like to output the results like this
<li><div class="colorblock" style="background-color:#89288f"></div> <div class="legend">This title</div></li>
<li><div class="colorblock" style="background-color:#89228f"></div> <div class="legend">My title</div></li>
Upvotes: 0
Views: 57
Reputation: 1576
http://api.jquery.com/jQuery.each/ is a great place to look for an answer to your question. Your key issue will be decide whether to use 1 or 2 selectors. 2 might be simpler to get you going here - the first to pick all divs with class legend
$('div.legend').each(data,function(i,v){
$(this).text=v.legend;
});
You may want to check that data has more or equal elements to the number picked in the selector.
You'd do something similar with the $('div.colorblock').each() using the .attr('style',value)
You could use 1 selector and look at the div child elements of the
Upvotes: 0
Reputation: 20471
$.each( data, function( key, val ) {
$("#id_of_your_ul").append('<li><div class="colorblock" style="background-color:'+ val.color +'"></div> <div class="legend">'+ val.legend +'</div></li>');
});
Upvotes: 1
Reputation: 388316
Use jQuery.map and .join()
var string = $.map(data, function(data, index){
return '<li><div class="colorblock" style="background-color:#' + data.color + '"></div> <div class="legend">' + data.title +'</div></li>'
}).join('');
Demo: Fiddle
Upvotes: 2
Reputation: 3317
I think the documentation gives a good explanation of how to use .each http://api.jquery.com/jQuery.each/
$.each(data, function(index, value) {
// create div element with data
// append the new div to the DOM
});
Upvotes: 0