The below code is simple example I came up with to show how to utilize dynamic comboboxes with JavaScript. Doing so can do a few things:
1) Distribute more of the "work" to the client's system
2) Greatly increase the efficiency of your site by reducing the number of pages that need to be served up
3) Present a more user-friendly interface to your users
In the below example you must specify a city that is closest to you. Instead of listing many cities in one combobox, you first select what region of the United States you live in. A second combobox is then populated based on what cities are in that area. As you user, you now only have to select a few cities instead of all of them in one list. This is an easy concept and thing to do, but most sites you see don't utilize it:
Code:
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
/*
1. Create a multi-dimensional array that holds the three main REGIONs of the United States
Array Index Region
------------------------
0 East Coast
1 Midwest
2 West Coast
2. Each REGION will hold CITY values in its own array
*/
var REGION = new Array( new Array(), new Array(), new Array() );
function AddCITY(intRegion, strCity) {
//Purpose: Insert a new CITY into the specified REGION (intRegion 0-2)
//insert a new CITY into this REGION and then increase its size
REGION[ intRegion ][ REGION[ intRegion ].length++ ] = strCity;
}
function LoadCities() {
//Purpose: load the below CITY values into their corresponding arrays of the main REGION array
//add the east coast cities (REGION=0)
AddCITY(0,"New York, NY");
AddCITY(0,"Bangor, ME");
AddCITY(0,"Richmond, VA");
AddCITY(0,"Miami, FL");
AddCITY(0,"Atlanta, GA");
//add the midwestern cities (REGION=1)
AddCITY(1,"Chicago, IL");
AddCITY(1,"Minneapolis, MN");
AddCITY(1,"Des Moines, IA");
AddCITY(1,"St. Louis, MO");
AddCITY(1,"Madison, WI");
//add the west coast cities (REGION=2)
AddCITY(2,"San Francisco, CA");
AddCITY(2,"Reno, NV");
AddCITY(2,"Portland, OR");
}
function UpdateCombos(intREGION) {
//Purpose: Update the cboCITY combobox by dumping the appropriate REGION array into it
//Resize the number of entries shown in the cboCITY combo to equal the number of cities in
//this REGION (intREGION)
document.frm.cboCITY.length = REGION[intREGION].length;
//For each CITY in the array, add it to the combobox
for (x=0; x < REGION[intREGION].length; x++)
document.frm.cboCITY[x] = new Option(REGION[intREGION][x],REGION[intREGION][x]);
}
</SCRIPT>
</HEAD>
<BODY onLoad=LoadCities();>
<FORM NAME="frm">
<!-- The OPTION values of this combo coordinate with the "CITY" array indexes -->
<SELECT NAME="cboRegion" onChange=UpdateCombos(this.value); STYLE="width:135px;">
<OPTION VALUE=0>East</OPTION>
<OPTION VALUE=1>Midwest</OPTION>
<OPTION VALUE=2>West</OPTION>
</SELECT>
<SELECT NAME="cboCITY" STYLE="width:140px;"></SELECT>
</FORM>
</BODY>
</HTML>