Dojo FAQ: How can I create dependent or linked select controls using Dijit?

By on August 27, 2014 10:09 am

DojoFAQ

When building a select control in a form there are times where its available options need to change dynamically in response to a change in another control. For instance, a form with both country and state/province select controls might require the options in the state select to change based on the country select’s current selection. This is what we would call a dependent, or linked, select. One way to accomplish this is by watching changes in the selection state of one select and finding and setting the appropriate selection values on the other.

The selection values of Dijit Select widgets can be provided as an array of options objects or a dojo/store instance. We will walk through an example creating a dependent select for both types of source data.

Using options-based Selects

One way to associate the available selection options of a dependent select with its source is a with a simple map, which is what we do in the example below:

First we create a map containing the country options and city options for each country. Then we initialize a dijit/form/Select widget for both country and city, providing them their initial options and value and attaching them to the page. Finally, we add a change listener that updates the options attribute of the city select every the the country select is updated. One thing to keep in mind when changing a select’s options is that its selected value should also be set.

Using store-based Selects

We can use the same basic approach for select widgets that are driven by stores, but there are a few differences, as demonstrated by this example:

The first thing you may notice is the buildOptionsStore function that all of our options are now run through—this is just a convenience to minimize the boilerplate code needed to create our stores. Another notable difference is that we use the store property rather than options to set our source as a store. Also, unlike options-based Select widgets, we have to provide a labelAttr for the store to use. Finally, we needn’t bother with setting initial values when changing our citySelect‘s store—this is taken care of automatically.

Conclusion

Our examples here focus on linking two Dijit Selects but the same idea can be applied to other select-like widgets, such as dijit/form/ComboBox or dijit/form/FilteringSelect. Linking any two controls is just a matter of finding the right property to watch for changes and reacting appropriately.

Learning more

SitePen covers the use of Dijit in-depth in our Dojo workshops offered throughout the US, Canada, and Europe, or at your location. We also provide expert JavaScript and Dojo support and development services. Contact us for a free 30 minute consultation to discuss how we can help.