On Mar 5, 2014, at 1:35 PM, [email protected] wrote:
There’s a variety of plugins that do this, but here’s one:
You typically have two options:
- Write out all of the available options for your second select when the page
loads, then selectively hide/show some of them depending on the first select’s
- Make an ajax call back to your application when the first select is changed
which will return to you the available options to populate the second select.
This may be the best option if you have a lot of options in your selects.
seen option #1 done with optgroups, so you’d write out your second select with the
corresponding options for each option in the first select nested within optgroups.
You’d then selectively hide/show the options depending on what’s selected from the
first select. The advantage here is that when JS is not available, the user just
needs to scroll through the second select to find the options that correspond to
their selection from the first select. It’s not ideal, but it’s a reasonable
And I just want to add (just answered a couple questions in a row about
this on SO) that you should not rely on stuffing HTML into the
tag to alter its options. This will work in a couple of browsers:
document.getElementById(‘my_picker’).innerHTML = ‘Whatever’;
but it will fail silently and weirdly in several others. The best way to
build up a picker from an Ajax response is to get a JSON (or other
array) of value/text pairs and build up the option elements inside a
my_picker.options[my_picker.options.length] = new Option(
elm[‘text’], elm[‘value’] );
Hope this helps,