4

Is there a way to filter a multi-line select box using jQuery?

I'm a new to jQuery and can't seem to figure out the best way to do this.

For example if I have:

<select size="10">
   <option>abc</option>
   <option>acb</option>
   <option>a</option>
   <option>bca</option>
   <option>bac</option>
   <option>cab</option>
   <option>cba</option>
   ...
</select>

I want to filter this list based on a selection drop down with:

<select>
   <option value="a">Filter by a</option>
   <option value="b">Filter by b</option>
   <option value="c">Filter by c</option>
</select>
4

1 回答 1

5

像这样的东西可能会奏效(假设你给你的'Filter by...'选择一个过滤器的id,然后过滤/其他选择一个id of otherOptions):

$(document).ready(function() {
    $('#filter').change(function() {
        var selectedFilter = $(this).val();
        $('#otherOptions option').show().each(function(i) {
            var $currentOption = $(this);
            if ($currentOption.val().indexOf(selectedFilter) !== 0) {
                $currentOption.hide();
            }
        });
    });
});

更新:正如@Brian Liang 在评论中指出的那样,您可能在将 <option> 标签设置为display:none时遇到问题。因此,以下应该为您提供更好的跨浏览器解决方案:

$(document).ready(function() {
    var allOptions = {};

    $('#otherOptions option').each(function(i) {
        var $currentOption = $(this);
        allOptions[$currentOption.val()] = $currentOption.text();
    });

    $('#filter').change(function() {
        // Reset the filtered select before applying the filter again
        setOptions('#otherOptions', allOptions);
        var selectedFilter = $(this).val();
        var filteredOptions = {};

        $('#otherOptions option').each(function(i) {
            var $currentOption = $(this);

            if ($currentOption.val().indexOf(selectedFilter) === 0) {
                filteredOptions[$currentOption.val()] = $currentOption.text();
            }
        });

        setOptions('#otherOptions', filteredOptions);
    });

    function setOptions(selectId, filteredOptions) {
        var $select = $(selectId);
        $select.html('');

        var options = new Array();
        for (var i in filteredOptions) {
            options.push('<option value="');
            options.push(i);
            options.push('">');
            options.push(filteredOptions[i]);
            options.push('</option>');
        }

        $select.html(options.join(''));
    }

});
于 2009-05-11T14:40:55.057 回答