Associative Arrays


Associative Arrays.  So far we have only talked about arrays who's elements can be accessed using a numerical index.  Now we move on to arrays that use other sorts of identifying characteristics such as a name or maybe a date/time to identify the element.  

I will work one example where we modify an earlier example.  Remember the quick jump menu to schools in my past that linked to other home pages for the onChange event in a select/drop down box.  We will modify this so that the link for the school appears in a text box when the user clicks on each particular school name.  All of the links will be stored in an associative array and accessed appropriately to fill the contents of the textbox with the onChange event.

You should copy the following code and put it in a file called DisplayURL.html.


<title>A Quick Jump to Some Universities</title>
<script language="JavaScript">
var URLs = new Array();
URLs["MSU"] = "";
URLs["Purdue"] = "";
URLs["Rider"] = "";
URLs["Syracuse"] = "";
URLs["UTenn"] = "";
URLs["VaTech"] = "";

function displayURL(URLs, the_site_name)

var school_site = URLs[the_site_name];
window.document.FindOldU.txtURLLocation.value = school_site;



<body bgcolor="#666699">

<p><b><font size="5" color="#C0C0C0">A Quick Jump Menu to the URLs of Universities in My Past</font></b></p>

<form name="FindOldU">

<div align="center">
<table border="0" cellpadding="4" cellspacing="0" width="500">
<p align="right"><font size="4" color="#CCCCFF"><b>School Name:</b></font></td>

<select name="cboUniversities" size="1" onChange="displayURL(URLs, this.options[this.selectedIndex].value);" >
<option value="MSU">Michigan State University
<option value="Purdue">Purdue University
<option value="Rider">Rider University
<option value="Syracuse">Syracuse University
<option value="UTenn">University of Tennessee
<option value="VaTech">Virginia Tech

<p align="right"><font size="4" color="#CCCCFF"><b>URL:</b></font></td>
<td><input type="text" name="txtURLLocation" size="30"></td>




When this is uploaded you should get something like the following.



Notice that we have defined and initialized the array outside of the function and it is passed to the function using only its name.  Also notice we used the this reference/operator to identify the selection in the select/drop down box.