Keyup filter multiple lists with headers with jQuery

房东的猫 提交于 2019-12-11 17:59:56

问题


I'm trying to filter multiple lists (books of specific categories) with headers (category name) on keyup with jQuery. I want to only filter search the items within the list (the specific books), but not filter the headers. If a list is empty, the header (category name) should disappear. What I have so far works on filtering the multiple lists, but headers don't disappear if their list is empty. I would also like to exclude the .custom-books list from filter.

HTML:

<input type="text" id="search" />

<ul id="workflow_books">    
<li>
    <h6 class="custom"> Custom Books</h6>

    <ul>
        <li class="custom-books">
            <a>Don't see your book in our list? Add it yourself!</a>
        </li>
    </ul>
</li>

<li>
    <h6>Academic</h6>

    <ul>
        <li>
            <a>Academic Book One</a>
        </li>

        <li>
            <a>Academic Book Two</a>
        </li>
    </ul>
</li>

<li>        
    <h6>Botany</h6>

    <ul>
        <li>
            <a>Botany Book One</a>
        </li>

        <li>
            <a>Botany Book Two</a>
        </li>
    </ul>
</li>
</ul>

and my jQuery:

var $products = $('#workflow_books li ul li a')

$("#search").keyup(function() {
    $products.show().filter(function() {
        return !re.test($(this).text());
    }).hide();
})

Any ideas?

Thanks and High Fives! Mike


回答1:


var $products = $('#workflow_books li ul:not(:first)');
$("#search").keyup(function() {
    var val = this.value.trim();
    if(!val) $('li:hidden', '#workflow_books').show();
    else {
        $('li:hidden', $products).show();
        $('li', $products).filter(function() {
            var re = new RegExp(val, 'ig');
            return !re.test($('a', this).text());
        }).hide();
        $products.each(function() {
            if($('li:visible', this).length == 0) $(this).parent('li').hide();
            else $(this).parent('li').show();
        });
    }
});

Working Demo




回答2:


Here you go, this will filter them, ignoring the first list, by the beginning of the string. Let me know if you need something more specific.

var $products = $('#workflow_books ul:not(:first)');

$("#search").keyup(function() {
    var input = this.value;    

    $products.each(function() {
        var $this = $(this),
            $matches = $this.children('li').filter(function() {

                return $(this).children('a').text().toLowerCase().indexOf(input) === 0;
            });

        if($matches.length > 0) {
            $this.children().hide();
            $this.parent().show(); 
            $matches.show();            
        } else {
         $this.parent().hide();   
        }
    });
})​;​


来源:https://stackoverflow.com/questions/10625811/keyup-filter-multiple-lists-with-headers-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!