One of my major sites that I work with is a purely data driven site where all the text, page layout and editable HTML content is customisable and driven from settings within a database. On a number of sites that use this product a number of the controls are list boxes that are all linked together in a hierarchal chain where the selected value(s) of one list will determine the available options in another. A good example is a chain of locations such as Country, Region and Town. When you select England from the Country list the Region list is populated with the various options within that country. There are various ways you can acomplish doing this including:
- Submitting the page on each list item selection. Gathering the data from the server and then reloading the page showing the appropriate options in the subsequent list.
- Populating client side arrays with all possible values for each list in the chain when the page first loads. Then when selections are made a function call will do lookups within the various arrays and populate the list accordingly.
- Use AJAX so that when a selection is made on one list the data for the subsequent list is gathered behind the scenes and a callback function populates the subsequent list.
Each option has its own merits but I use the last option because its user friendly and fast. I recently had to rewrite the way I handled these linked lists and a demo of the Javascript object is on this page. The features and functionality that the object supports is listed below:
- No limit on the number of lists linked together in a chain.
- Handle multiple groups of linked lists on one page.
- Ability to customise per list the wording for default options such as "Please Select", "Any", "No Records".
- On loading a list any options that were previously selected must be re-selected e.g saved options.
- An option that on first loading a page populates a child list with all possible options even though nothing in the parent list maybe selected.
Linked List Demonstration
The example form below shows the linked list object working running 2 groups of linked lists together with each group containing 3 lists Country > Region > Town / City. I have also outputted my debug code into a div at the bottom of the page as its always helpful to see whats going on as you play about with an example.