A not-uncommon scenario in a form is the case of City/State selectors. If the user chooses a state, it would be nice to let them choose the city without seeing cities from other states. This same principle can apply to many situations where the value of one selector is used to limit the selections available in another.
This kind of thing typically requires some fairly complex code because real-world forms applications tend to be complicated. Most of the time, if you need this kind of dynamic behavior in your form, you’re either going to code it yourself if you’ve got the skills or hire someone with the skills to do it.
A Simple Approach
What if all we needed was something simple like our first example?
There is a way to do this that doesn’t require a lot of code, as long as all the options can be present when the form is loaded, and there is a simple relationship between the two selectors. The basic idea is you have a “parent” selector and a “child” selector. The parent selector determines which options are available in the child selector…in our example the parent is the state selector and the child is the city selector.
Note: this tutorial won’t work for Chosen selectors, it is for regular dropdown selectors only.
Here is How That Gets Set Up
The way this works is the child selector’s options are divided into groups using “optgroups” that correspond to the selections in the parent selector. For example, if you’ve got 25 states, the city selector will have 25 optgroups that have labels that match the states. Each of those optgroups will contain the cities for that state. This way, we know that when a state is selected, we can use the value of that selection to find it’s corresponding group in the cities, and only show the members of that group: the cities in that state.
In Participants Database, the cities dropdown is set up with a values string like this (this is not the complete string, just enough to show how it is structured):
Alabama::optgroup, Birmingham, Montgomery, Mobile, Huntsville, Alaska::optgroup, Anchorage, Arizona::optgroup, Phoenix, Tucson, Mesa, Chandler, Gilbert, Glendale, Scottsdale, Tempe, Peoria, Surprise, Arkansas::optgroup, Little Rock, California::optgroup, Los Angeles, San Diego
And the “state” selector gets a values string like this:
Alabama::AL, Alaska::AK, American Samoa::AS, Arizona::AZ, Arkansas::AR, California::CA
Note: this code was updated on February 17, 2017 to allow the child’s value to be shown initially
And just so you can see it in action, here it is in a signup form template. You’ll notice that it is simply inserted at the top, after the PHP close tag and before the <div> tag. When the template is loaded the script goes into action, putting a handler on the parent field so that when a selection is made, the child selector will show the appropriate selections.