amazedinc
amazedinc

Reputation: 418

jQuery array to unordered list

I have the following array:

var sherbert = [{ 
    flavor: "orange mango",
    cost: 2
},{
    flavor: "lemon lime",
    cost: 4
}];

Using jQuery how can I create a function that writes these as LI items like:

<li>flavor : orange mango<span>cost : 2</span></li>
<li>flavor : lemon lime<span>cost : 4</span></li>

Upvotes: 1

Views: 6458

Answers (4)

Ashima
Ashima

Reputation: 4824

Here you go:

var ul = $('<ul>');

for (var i = 0; i < sherbet.length; i++ ) {
    var li = $('<li>');
    var item = sherbet[i];
    for(var key in item) {
        var span = $('<span>');
        var text = key + ": " + item[key]; // flavour: orange
        span.html(text); // <span>flavour: orange</span>
        li.append(span); // <li><span>flavour: orange</span><span>cost: 2</span></li>
    }
ul.append(li);
}

Here, you don't really have to hard code any values such as 'flavour' or 'cost'. This code gives you flexibility to alter these texts into something else or add something to it like "size: 10oz" etc.
You just gotta add these additonal values to your array and this code will handle it all!

Upvotes: 0

Aheinlein
Aheinlein

Reputation: 472

<script>
var sherbert = [{ 
    flavor: "orange mango",
    cost: 2
},{
    flavor: "lemon lime",
    cost: 4
}];
$(document).ready(function(){
    $(sherbert).each(function(i, el){
        var li = document.createElement('li');
        li.innerHTML = "flavor : " + el.flavor + " <span>cost : " + el.cost + "</span>";
        $("#listItems")[0].appendChild(li);
    });
});
</script>
<body>
    <ul id="listItems">
    </ul>
</body>

Upvotes: 0

Derek
Derek

Reputation: 4751

Iterate over your sherbert object and add the new HTML as a new li in your desired list.

$.each(sherbert, function(index, dessert) {
    var new_html = "Flavor : " + dessert.flavor + "<span>cost : " + dessert.cost + "</span>";
    $('ul').append($('<li></li>').html(new_html));
});

Upvotes: 0

bottens
bottens

Reputation: 3892

Something like this should work, I did not test this code.

here are the documentation for jquerys each and append functions:

http://api.jquery.com/each/

http://api.jquery.com/append/

$listSelector = $("#list") //Your list element

$.each(sherbert, function(i, obj) {
    $listSelector.append("<li>flavor : "+obj.flavor+"<span>cost : "+obj.cost+"</span></li>")
});

Upvotes: 3

Related Questions