I have 6 Gmail invites. If anyone wants one, shoot me an email or leave your email address in a comment.
Monthly Archives: September 2004
Dynamic Select Lists with JavaScript
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.
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).
var states = new Array();
states['CA'] = new Array('Orange','Los Angeles','Riverside','Marin','Stanislaus','Merced','Butte');
Now that we have our data, let’s create a function to populate the second (counties) select list.
function updateCounties(stateName)
{
var theForm = document.forms[0];
var theSelect = theForm.counties;
var theOption;
}///~ End updateCounties()
// 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
// 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;
// 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
// Now we append it to the select list like so
theSelect.options[theSelect.options.length] = theOption;
Not too difficult, no?
In your state select list then, you would call this function via onChange.
Awe Man!
Well, yesterday a co-worker sent out an email to everyone because he was selling his 1969 Mercedes Benz 280S. The car looks to be in very good condition (both internally and externally) and he only wanted $1500. I asked about it and set up a time to go check it out. I was going to go sometime on Saturday to have a look at it and possibly buy it. I was kind of stoked. I need a car for the rainy season (since I don’t really want to ride the motorcycle in the rain) and this would have been a cool car to cruise to work.
Then, I was outside taking a break with some other people and learned that this other lady’s mother just bought the car! Damnit! What the !
Thanks a lot ROSE!