Darren
Darren

Reputation: 139

How do I loop through this array using jquery?

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

Answers (4)

nickL
nickL

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

  • 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.

    Upvotes: 0

  • kei
    kei

    Reputation: 20471

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

    Upvotes: 1

    Arun P Johny
    Arun P Johny

    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

    spullen
    spullen

    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

    Related Questions