I have 2 drop-down menus. User selects something from the first one, then the options that are displayed within the second are filtered based on the first selection.
My strategy is to .hide() all of the options in the second drop-down if they are not relevant.
The function I wrote properly identifies which items in the second drop-down list should be hidden and adds the style=”display:none” attribute to those options.
The problem is that the second drop-down list appears to have nothing in it after you select something from the first.
Here is all the JS. The HTML should be able to be inferred fairly easily. The items in the second drop-down list have been tagged with a class name that matches an option from the first option list.
$(document).ready(function () {
$('.part-type').change(function () {
$(this).show();
var part_type = "."+$(".part-type option:selected").text().toLowerCase();
$('.part').children().filter(":not("+part_type+")").hide();
})
});
Thanks to all my friends on SO.
Link to my work in action on JsFiddle –> http://jsfiddle.net/hwD8K/
Unfortunately, you can’t use CSS to affect the display of
options in aselect.Your best bet is probably to store the values in a data field on the
select, and then filter that data field on every change and re-set the contents of theselectevery time.Or, instead of show() and hide() you could probably detach the undesired
options from the DOM and reattach them later.For more thoughts on this, see this question:
How can I hide select options with JavaScript? (Cross browser)