Frage

Gibt es eine Möglichkeit, einen mehrzeiligen Auswahlbox mit jQuery zu filtern?

Ich bin ein neuer zu jQuery und kann nicht scheinen, den besten Weg, um herauszufinden, dies zu tun.

Zum Beispiel, wenn ich:

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

Ich mag diese Liste filtern, basierend auf einer Auswahl Dropdown mit:

<select>
   <option value="a">Filter by a</option>
   <option value="b">Filter by b</option>
   <option value="c">Filter by c</option>
</select>
War es hilfreich?

Lösung

So etwas könnte den Trick tun (vorausgesetzt, Sie geben 'Filtern nach ...' wählen Sie eine ID von Filter und das gefilterte / andere eine ID von wählen 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();
            }
        });
    });
});

UPDATE: Wie @ Brian Liang in den Kommentaren darauf hingewiesen, könnten Sie Probleme haben, die Einstellung der

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

});
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top