Question

Y at-il un moyen de filtrer une boîte de sélection multi-ligne en utilisant jQuery?

Je suis un nouveau jQuery et ne peut pas sembler trouver la meilleure façon de le faire.

Par exemple, si je:

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

Je veux filtrer cette liste basée sur une sélection déroulant avec:

<select>
   <option value="a">Filter by a</option>
   <option value="b">Filter by b</option>
   <option value="c">Filter by c</option>
</select>
Était-ce utile?

La solution

Quelque chose comme cela pourrait faire l'affaire (en supposant que vous donnez à votre « Filtrer par ... » sélectionner un identifiant de Filtre et filtré / autre sélectionner un identifiant de 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();
            }
        });
    });
});

MISE À JOUR: Comme Liang a souligné @ Brian dans les commentaires, vous pourriez avoir des problèmes de réglage

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

});
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top