jQuery过滤

时间:2009-05-11 14:20:10

标签: javascript jquery filtering

有没有办法使用jQuery过滤多行选择框?

我是jQuery的新手,似乎无法找到最佳方法。

例如,如果我有:

<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>

我想根据以下选项下拉列表来过滤此列表:

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

1 个答案:

答案 0 :(得分:5)

这样的事情可能会有所帮助(假设您给'过滤器'过滤器'选择过滤器的ID,过滤器/其他器件选择 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在评论中指出的那样,您可能在设置&lt;选项&gt;时遇到问题。标签为显示:无。因此,以下内容应该为您提供更好的跨浏览器解决方案:

$(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(''));
    }

});