tags:

views:

188

answers:

3

I have a DIV. I want to dynamically generate a bulleted list inside the DIV using jQuery with a items list I have with me

for (cnt = 0; cnt < someList.length; cnt++) {
                         someList[cnt].FirstName + ":" + someList[cnt].LastName + "<br/>"
                        // what to write here?
                    }

Thanks!

+4  A: 

Script:

$(function(){
    someList = [ {FirstName: "Joe", LastName: "Smith"} ,
                 {FirstName: "Will", LastName: "Brown"} ]

    $("#target").append("<ul id='list'></ul>");
    $.each(someList, function(n, elem) {
       $("#list").append("<li>" + elem.FirstName + " : " + elem.LastName + "</li>");
    });
});

and html:

<div id="target" />
kgiannakakis
How do I write this in the $.each you suggestsomeList.d[i].FirstName
Musa
Thanks for your solution..I used the for loop and did it!
Musa
How is your array formed? $.each can iterate both arrays and hashes. When iterating arrays you can get both the element (elem) and the index (n) in the callback. If your array contains array elements, you need to call $.each inside the callback.
kgiannakakis
A: 

hacky

var list = "<ul>"
for (cnt = 0; cnt < someList.length; cnt++) {
    list += "<li>" + someList[cnt].FirstName + ":" + someList[cnt].LastName + "</li>"
}
list += "</ul>";

no even bothering with creating dom objects properly :)

Luke Schafer
+2  A: 

Keeping things as simple as possible. Using your existing javascript, You would just need to add this:

    $('#myDiv').append("<ul id='newList'></ul>");
    for (cnt = 0; cnt < someList.length; cnt++) {
          $("#newList").append("<li>"+someList[cnt].FirstName + ":" + someList[cnt].LastName+"</li>");
    }

Since your HTML already has the DIV:

<div id="myDiv"></div>
Jose Basilio
Thanks that did it!
Musa
Keeping it simple +1
ichiban