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






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 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.