Chained Selects Step-by-step: Implement the list group

Let's recall the steps to implement Chained Selects:

  1. define the content of select options, which would be referred to as a list group
  2. include the Chained Selects function script (chainedselects.js) in the page
  3. embed the definition of list group in the page, or include it if put in a JS file
  4. set up the form select lists as usual (or just set up some empty select lists)
  5. bind the form select lists to a list group when the page is loaded

We have the list group already:

// define a list group
addListGroup("vehicles", "makers");

// and its top list
addList("makers", "Toyota", "Toyota", "toyota-list");
addList("makers", "Honda", "Honda", "honda-list");
addList("makers", "Chrysler", "Chrysler", "chrysler-list");

// sub-list for toyora
addList("toyota-list", "Car", "Car", "toyota-car");
...

Let's say we save the content in a file and name it as content.js, then for step 2 and step 3 we would have the following setup in our page:

<head>
<script language="javascript" src="chainedselects.js"></script>
<script language="javascript" src="content.js"></script>
</head>

Of course we will need three select lists in our page:

<form>
<select name="maker"></select>
<select name="type"></select>
<select name="model"></select>
</form>

In IE, if we just use some empty select lists, they are quite narrow and won't adjust the width when being populated. We will need to define a width with CSS or create a dummy option to reserve the width, such as:

<select name="maker" style="width:200px"></select>
<select name="maker"><option>a long dummy option to reserve the width</option></select>

After that, we can set up the BODY onload handler to bind the list group to the three select lists:

<body onload="initListGroup('vehicles', document.forms[0].maker, document.forms[0].type, document.forms[0].model);">

Click [ here ] to see a demo page.


On the demo page, if you refresh the page, the select lists will restore to the original state and we will lose the selections we've made. To "remember" the selections, we can turn on the cookie option in the initListGroup() call.

The initListGroup() call has the following syntax:

initListGroup("list-group-name", form-select-1, form-select-2, ..., form-select-N, "cookie-name", callback-function);

The "cookie-name" parameter and callback-function parameter are optional. If we want a persistent list group, we just need to provide a name for the "cookie-name" parameter, such as:

<body onload="initListGroup('vehicles', document.forms[0].maker, document.forms[0].type, document.forms[0].model, 'save');">

Click [ here ] to see a persistent demo page.

[ Set up the callback function ] [ Back to main page ]

# # #