He’s making a list!

20150830_132921

So thus far we have created a simple JavaScript HTML app.  We have separated the code from the page.    So the question here is why are we doing it?  Well I thought it would be fun to see if we could do our last states map project using, a different programming language.  I know I can do it in C# & V.NET but how about JavaScript.  OK, so to this first we are going to make the data available in a list. That means first we need to add list to our HTML page.  There are two kinds of list in HTML <ul> or (unordered listed), and <ol> or (ordered list).   In this case we are going to use an unordered list.  To this we will use the following code:

<!DOCTYPE html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<title>Javascript</title>
myList.js”>
<style>
</style>
</head>
<body bgcolor=”#E6E6FA”>
<hr>
<ul id=”stateList”>
</ul>
<hr>
</body>
</html>

This give us a list,  but what about showing data in the list. Well to do that we will use the <li> or list item element of the list. We then put it into our code behind. Our code behind file is called “myList.js” and the HTML file should be called  “myList.HTML” . Remember both will need to be at the same folder. Here’s the code;

window.onload = function()
{
var test = [
“Alabama”,
“Alaska”,
“Arizona”,
“Arkansas”,
“California”,
“Colorado”,
“Connecticut”,
“Delaware”,
“Florida”,
“Georgia”,
“Hawaii”
]
var test2 = [
“Montgomery”,
“Juneau”,
“Phoenix”,
“Little Rock”,
“Sacramento”,
“Denver”,
“Hartford”,
“Dover”,
“Tallahassee”,
“Atlanta”,
“Honolulu”
]
for (var i = 0; i < test.length; i++)
{
//create new li element
var newStateListItem = document.createElement(“li”);
//create new text node
var stateListValue = document.createTextNode(test[i] + “: ” + test2[i] );
//add text node to li element
newStateListItem.appendChild(stateListValue);
//add new list element built in previous steps to unordered list
//called stateList
stateList.appendChild(newStateListItem);
}
}

That’s a lot of stuff. Let’s break it down.  We need something to hold our data. We are using two arrays, ( yes I know we could use one) but this is an attempt to keep things very simple later on. This is done with the var test = [data,data] statement.   Of course test2 holds the capital names. The next part of the function iterates thru the data and creates a <li>, (list item) for each.  The list item is give the value of the arrays and added to the stateList using appendChild.   This should give you the following output.

list

So that should get us started.