jQuery disable SELECT options based on Radio selected (Need support for all browsers)

The proper way to achieve the functionality you want is just to remove the options. As you discovered the hard way, disabling individual options is not supported particularly well across browsers. I just woke up and feel like programming something so I whipped up a small plugin to easily filter a select based on a radio’s selected ID attribute. Although the rest of the solutions will get the job done, if you are planning on doing this throughout your app this should help. If not, then I guess it’s for anyone else that stumbles upon this. Here is the plugin code you could stash away somewhere:

jQuery.fn.filterOn = function(radio, values) {
    return this.each(function() {
        var select = this;
        var options = [];
        $(select).find('option').each(function() {
            options.push({value: $(this).val(), text: $(this).text()});
        });
        $(select).data('options', options);
        $(radio).click(function() {
            var options = $(select).empty().data('options');
            var haystack = values[$(this).attr('id')];
            $.each(options, function(i) {
                var option = options[i];
                if($.inArray(option.value, haystack) !== -1) {
                    $(select).append(
                    $('<option>').text(option.text).val(option.value)
                    );
                }
            });
        });            
    });
};

And here is how to use it:

$(function() {
    $('#theOptions').filterOn('input:radio[name=abc123]', {
        'abc': ['a','b','c'],
        '123': ['1','2','3']        
    });
});

The first argument is a selector for the radio group, the second a dictionary where the keys are the radio ID to match, and the value is an array of what select option values should remain. There’s a lot of things that could be done to abstract this further, let me know if you are interested and I could certainly do that.

Here is a demo of it in action.

EDIT: Also, forgot to add, according to the jQuery documentation:

In jQuery 1.3 [@attr] style selectors were removed (they were previously deprecated in jQuery 1.2). Simply remove the ‘@’ symbol from your selectors in order to make them work again.

Leave a Comment