简体   繁体   中英

Using a <select multiple> to filter divs

Say I have like:

<div class="numbers one two three">...</div>
<div class="numbers one three five">...</div>
<div class="numbers two four six">...</div>
<div class="numbers one two four">...</div>

and I have a select like:

<select id="filternumbers" multiple="multiple">
    <option value="one">One</option>
    <option value="two">Two</option>
    <option value="three">Three</option>
    <option value="four">Four</option>
    <option value="five">Five</option>
    <option value="six">Six</option>
</select>

How do I get the select to filter divs based on my selection, say "two" and "four" - meaning only last two divs should be visible?

I know I can do this for single select menus:

$('#filternumbers').on('change', function () {
    var number = $(this).val();
    $(".numbers").hide();
    $(".numbers").hasClass(number).show();
});

But how do I do it for a multi select?

You need to $.fn.filter divs by combination of class names:

 $('#filternumbers').on('change', function () { var number = $(this).val(); var classNames = '.' + number.join('.'); $(".numbers").hide().filter(classNames).show(); });
 .numbers {display: none;}
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="filternumbers" multiple="multiple"> <option value="one">One</option> <option value="two">Two</option> <option value="three">Three</option> <option value="four">Four</option> <option value="five">Five</option> <option value="six">Six</option> </select> <div class="numbers one two three">one two three</div> <div class="numbers one three five">one three five</div> <div class="numbers two four six">two four six</div> <div class="numbers one two four">one two four</div>

You can check all the values which are checked first and run each() for checked values and then show the requied values using filter

$('#filternumbers').on('change', function () {
    $(".numbers").hide();
    $('#filternumbers option:selected').each(function() {
        var number = $(this).val();
        var classNames = '.' + number;
        $(".numbers").filter(classNames).show();
    });

});

refer jsfiddle http://jsfiddle.net/gsmd2jd3/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM