0

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>
2
  • Are you sure you want to use jQuery and not PHP? Why are you doing this on the client side? Commented Mar 22, 2013 at 16:15
  • Need to use jquery because the result needs to be displayed in realtime based on user actions. Commented Mar 22, 2013 at 16:17

4 Answers 4

2

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

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

Comments

1

DEMO

$.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>');
});

Comments

0

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
});

Comments

0

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

  • elements. The first using the .attr('style',value) and the second looking at text. I think right now you may just want to get it working and then optimise selector usage depending on your page layout.

  • Comments

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.