jQuery and ASP.NET

June 9, 2009

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



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP 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 has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

3 Responses to "Generating a Bulleted List dynamically using jQuery"
  1. SwedishChef said...
    July 23, 2009 4:15 AM

    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

  2. Peter Eysermans said...
    August 12, 2009 11:38 PM

    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.

  3. Suprotim Agarwal said...
    August 14, 2009 5:06 AM

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

 

Copyright © 2009-2011 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions