I was asked last week by a friend how to create drop down (select) lists on the fly. I’ve been doing a lot lately and don’t really think much about it, but it’s relatively easy. The idea is to get all the data you’re going to need and store it in JavaScript array. Let’s say you have a select list full of states. When a user selects a state (say Kah-lee-fo-nee-uh) you want another select list to display the counties for that state. For brevity, I’m not going to list all the counties in this state. That would be overkill for this example.
<p>Using the onChange event handler in the first select list, we can trigger a function that updates the second select list with the proper data. I digress, first we need the data (the states and counties for each state).</p>
<pre><code>var states = new Array();
states['CA'] = new Array(’Orange’,'Los Angeles’,'Riverside’,'Marin’,'Stanislaus’,'Merced’,'Butte’);
<p>Now that we have our data, let’s create a function to populate the second (counties) select list.</p>
<pre><code>function updateCounties(stateName)
{ var theForm = document.forms[0]; var theSelect = theForm.counties; var theOption; }///~ End updateCounties()
<pre><code>// Let's do a check to make sure the user has selected
// something valid (i.e. not the first item in the list // which is just a label…like ‘Select a State’) if(theSelect.selectedIndex != 0) { }///~ End if
<pre><code>// First we set the length of the select list to 0
// to clear any previous entries. Otherwise, it will // just keep adding to the select list theSelect.options.length = 0;
<pre><code>// Now we begin to loop through the appropriate array
// depending on which state they have chosen for(var i = 0; i < states[stateName].length; i++) { // Set the ‘theOption’ variable to the Option() // function passing it the values in the array. // eg: Option(optLabel, optValue); theOption = new Option(statesstateName, i); }///~ End for
<pre><code>// Now we append it to the select list like so
theSelect.options[theSelect.options.length] = theOption;
<p>Not too difficult, no?</p>
<p>In your state select list then, you would call this function via onChange.</p>
<p>Piece o cake!</p>
<p>That’s about it. This is just a basic example. I don’t really have any working samples quite yet. And, to be honest, the preceding code wasn’t tested. To be brutally honest, it’s like 2:30 in the morning. Iif you find errors and such, that’s probably why. In any case, send me the fix and I’ll update the post.</p>
<p>Good night!</p>











hello, really wondered if u have update to the coding. been trying it but did not work as it should. can u enlighten me .. please?