Hide Select Options Across All Browsers
A jQuery function to toggle the visibility of select options that works consistently in all browsers.
Hiding options in an HTML <select> element doesn’t work consistently across all browsers. Here’s a jQuery solution that handles it everywhere.
The function
jQuery.fn.toggleOption = function(show) {
jQuery(this).toggle(show);
if (show) {
if (jQuery(this).parent('span.toggleOption').length) {
jQuery(this).unwrap();
}
} else {
if (jQuery(this).parent('span.toggleOption').length == 0) {
jQuery(this).wrap('<span class="toggleOption" style="display: none;" />');
}
}
};
How to use it
// Hide an option
$(selector).toggleOption(false);
// Show an option
$(selector).toggleOption(true);
The trick is wrapping the hidden option in a <span> with display: none. This ensures compatibility with browsers that ignore display: none directly on <option> elements.