Welcome to WebmasterWorld Guest from 54.204.198.71

Forum Moderators: open

Message Too Old, No Replies

add elements dynamically to an unordered list

     
8:12 pm on Mar 27, 2012 (gmt 0)

Junior Member

5+ Year Member

joined:May 18, 2011
posts:90
votes: 0


HI there, I am looking at some exercises found here and there on the net, and I am attempting to resolve one which basically asks to populate a unordered list with items. I am having quite a few problems, although I'd say that's probably an easy thing to do. ANyway, code's here:
HTML:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>test</title>
<link rel = "stylesheet" type = "text/css" href = "style.css">
<script type = "text/javascript" src = "script.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>

<body onload = "getCities()">
<div id = "cities">
<ul id = "cities_list">
<li></li>
<li></li>
<li></li>
<li></li>


</ul>

</div>
</body>

</html>


CSS:

#cities
{

background-color:green;
width:100%;
height: 400px;

}

#cities_list
{

display:none;

}

javascript:

var city_arr = new Array("London", "Madrid", "Leeds", "Barcelona");

var index;

function getCities(){

for (index = 0; index < city_arr.length; index++)

{

$("li#cities_list").html("city_arr[index]").show('fast');

}


}



Now, the idea is that I have already an unordered list on my html. The list is hidden with css and the script should add the elements of the array in the list, but it's not happening
Any idea as to why? and perhaps suggestion as to how to proceed please?
thanks
11:36 pm on Mar 27, 2012 (gmt 0)

Senior Member

WebmasterWorld Senior Member 10+ Year Member

joined:Nov 3, 2005
posts:1585
votes: 0


var index;
would be better declared within function getCities as it is only used inside this function.

.show('fast')
You are doing this on each li, it is the ul that is hidden, move to after the for loop.
$("#cities_list").show('fast');

$("li#cities_list").
This will fail as the li does not a id on it, instead try
$("#cities_list").append('<li>'+city_arr[index]+'</li>');
and remove empty li's from html.
10:22 pm on Mar 28, 2012 (gmt 0)

Junior Member

5+ Year Member

joined:May 18, 2011
posts:90
votes: 0


yes, thanks daveVk that works a treat. I didn't know that $("li#cities_list").html("city_arr[index]").show('fast'); the html method within the loop doesn't assign 4 bullet point to the list but at every run it clears the previous item and adds another one, therefore leaving me with only 1 bullet point. It took me a while to understand that, I simply thought that there was an error in my code.
cheers
 

Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members