I’m trying to write a function to update the “multiple” select (the second one below) such that when I select Method1 (from the first select), only the options 1A, 1B and 1C appears in the second select, and likewise for 2A, 2B… only when I select Method2. Is there a way to do this. Please help.
Many thanks in advance.
<select name="choices" onchange="updatesub()">
<option>Method1</option>
<option>Method2</option>
</select>
<select multiple="multiple" name="sub">
<option>1A</option>
<option>1B</option>
<option>1C</option>
<option>2A</option>
<option>2B</option>
<option>2C</option>
</select>
I don’t think there’s cross browser support for hiding select options.
Here’s one way to do it. Uses a more jQuery like method of handling events, so you’ll need to remove the inline
onchangefrom the HTML.Try it out: http://jsfiddle.net/W9KvT/
If you don’t want to generate these on the fly each time, you could create each option string, and save them in the array, loading them in a similar manner.
Try it out: http://jsfiddle.net/W9KvT/1
EDIT: As noted by @You, in order to ensure compatibility with browsers that have javascript disabled, it is best to have all the available options available on page load. Then you can use the code above to overwrite them for js browsers.
The
<optgroup>elements from @You’s answer would be an excellent idea in that case.