Hide and show options in a select dropdown

Problem: You want to hide and show certain <option>s in a <select> form element, but you can’t apply ‘display: none’ CSS to them because they’re the wrong kind of DOM element. Toggling the ‘disabled’ property only grays the <option> out, which isn’t as good as hiding it completely.

Solution: Using jQuery, we can .detach() the <select> into a global variable on page load, then add back only the <option>s you want on demand. Say you only want to show <option>s that have a certain class (http://jsfiddle.net/mblase75/Afe2E/):

var $sel = $('#sel option').detach(); // global variable

$('a').on('click', function (e) {
    e.preventDefault();
    var c = 'name-of-class-to-show';
    $('#sel').empty().append( $sel.filter('.'+c) );
});

At first I thought you’d have to .clone() the <option>s before appending them, but apparently not. The original global $sel is unaltered after the click code is run.


If you have an aversion to global variables, you could store the jQuery object containing the options as a .data() variable on the <select> element itself (http://jsfiddle.net/mblase75/nh5eW/):

$('#sel').data('options', $('#sel option').detach()); // data variable

$('a').on('click', function (e) {
    e.preventDefault();
    var $sel = $('#sel').data('options'), // jQuery object
        c = 'name-of-class-to-show';
    $('#sel').empty().append( $sel.filter('.'+c) );
});

 

Leave a Reply

Your email address will not be published. Required fields are marked *

*