简体   繁体   中英

Filter a list (ul>li) using dropdown list

I have this code below that filters a list based off a selected radio button ( JSfiddle ).

How do I change it, so I can use a drop down list to filter it ( select>option tags) ?

<input name="name" value="_a" id="_a" type="radio"/><label for="_a">A</label>
<input name="name" value="_b" id="_b" type="radio"/><label for="_f">B</label>
<input name="name" value="_ab" id="_ab" type="radio" checked="checked"/><label for="_ab">A and B</label>
<br>
<select>
    <option value="_a">A</option>
    <option value="_b">B</option>
    <option value="_ab">A and B</option>
</select>

<ul id="mylist">
<li class="_ab _a">A1</li>
<li class="_ab _a">A2</li>
<li class="_ab _b">B1</li>
<li class="_ab _b">B2</li>
</ul>
<script>
$('input').click(function() {
        var selector = $('input:radio').map(function(){ 
            return this.checked ? '.' + this.id : ''; 
        }).get().join('');
        console.log(selector);  

        var all = $('li[class^="_"]');
        if(selector.length)
          all.hide().filter(selector).show();
        else all.show();
    });
</script>

You need to add a listener to the "select" tag. Look into .change() specification.

like this?

$('select').on('change', function (e) {

        var selector = "."+$(this).val();
        console.log(selector); 

        var all = $('li[class^="_"]');
        if(selector.length)
          all.hide().filter(selector).show();
        else all.show();
});

http://jsfiddle.net/8qmjjL3x/3/

$('select').on('change', function (e) {
        var selector = $('option').map(function(){ 
            return this.selected ? '.' + this.value : ''; 
        }).get().join('');
        console.log(selector);  

        var all = $('li[class^="_"]');
        if(selector.length)
          all.hide().filter(selector).show();
        else all.show();
    });

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