Generating a Bulleted List dynamically using jQuery

Recently I had to take a list of items from a service and display it in a Bulleted List dynamically created. The requirement was to use plain HTML and jQuery. Here’s how to do so:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Display Progress</title>
<
script src="Scripts/jquery-1.3.2.js"
type="text/javascript"></script>

<
script type="text/javascript">
$(document).ready(function() {
var geoList = [
{ Country: "India", State: "Delhi" },
{ Country: "US", State: "Alabama" },
{ Country: "US", State: "Georgia" },
{ Country: "US", State: "Texas" },
{ Country: "US", State: "NewYork" }
];
$('#LoadPage').append("<ul id='cList'></ul>");
for (i = 0; i < geoList.length; i++) {
$("#cList").append("<li>" +
geoList[i].Country + "-" +
geoList[i].State + "</li>");
}
});
</script>
</
head>
<
body>
<
form id="form1">
<
div>
<
div id="LoadPage">
</
div>
</
div>
</
form>
</
body>
</
html>



OUTPUT



image



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

3 comments:

SwedishChef said...

Nice. Simple and fast.

One thing you might want to consider, should you have a very large data set, is to concat the straing with li's and output that string instead of using append.

i.e.
var output = '';

and for each iteration in the loop,

output += " [LI] " + geoList[i].Country + "-" geoList[i].State + "[/ LI ]";

and then do something like $("#LoadPage").html('[UL]'+output+'[/ UL]');

replace brackets with greater/less than

Peter Eysermans said...

Nice example. You could use jquery to iterate through the collection instead of using a classic for. Like this:

$.each(geoList, function(index, geoItem)
{
$("#cList").append("[li]" + geoItem.Country + "-" + geoItem.State + "[/li]");
});

I find the code easier to read using $.each.

SwedishChef also points out a nice optimization by first creating a string of all your items and appending it all at once to the page.

Suprotim Agarwal said...

SwedishChef, Peter Eysermans : Those tips were neat! Thanks for sharing.