Hi I want to display a list of item inside
sample html code
<h3 id="game-filter" class="gamesection">
<span>Game</span></h3>
<div id="game-filter-div" style="padding: 0;">
<ul id="gamelist">
</ul>
</div>
code
var games = new Array();
games[0] = "World of Warcraft";
games[1] = "Lord of the Rings Online";
games[2] = "Aion";
games[3] = "Eve Online";
games[4] = "Final Fantasy XI";
games[5] = "City of Heros";
games[6] = "Champions Online";
games[7] = "Dark Age of Camelot";
games[8] = "Warhammer Online";
games[9] = "Age of Conan";
function pageLoaded(){
var list = "";
for(i=0; i<games.length; i++){
list ="<li>"+games[i]+"</li>";
$("#gamelist").append(list);
//document.getElementById("gamelist").innerHTML=list;
list = "";
}
}
Seems there is wrong with my js code. It doesn't output anything
There are so many things you are doing wrong in it.
Firstly, it is not pure javascript, its jquery.
you need to reference jQuery api to be able to use jQuery.
however, you can achieve what you want through pure javascript also.
Now let's look at your mistakes
you have created a function pageLoaded
, but have not called it anywhere. You need to call a function in order to make its logic work. Am assuming you want to call your pageLoaded
method when the page is ready. you can either call it on body load or simply inside jQuery's .ready i.e $(document).ready(function(){ pageLoaded()});
.
This method simply ensures, your logic executes when the dom is ready
you have written non-keyword, meaningless words inside your method "items in the array". remove it in order to make your function work. Am assuming you wanted to put a comment over there, put a comment like this inside script tag:
//items in the array
you are not concatenating new values to your list
variable, you are overwritting its content with each iteration, so instead of list ="<li>"+games[i]+"</li>";
this, do this
list +="<li>"+games[i]+"</li>";
finally, you are appending the list
to #gamelist
inside the for loop. do it outside the loop. once your list is complete. and remove the line list=" "
so place this line $("#gamelist").append(list);
outside the for loop.
try your function like this:
var games = new Array();
games[0] = "World of Warcraft";
games[1] = "Lord of the Rings Online";
games[2] = "Aion";
games[3] = "Eve Online";
games[4] = "Final Fantasy XI";
games[5] = "City of Heros";
games[6] = "Champions Online";
games[7] = "Dark Age of Camelot";
games[8] = "Warhammer Online";
games[9] = "Age of Conan";
$(document).ready(function(){
var list = "";
for(i=0; i<games.length; i++){
list +="<li>"+games[i]+"</li>";
}
$("#gamelist").append(list);
});
see this fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With