Filter multiple
    lists with jQuery

前端 未结 2 616
情书的邮戳
情书的邮戳 2021-02-05 09:51

I have multiple lists on one page (multiple categories of products) like this:

Category 1

  • item1<
相关标签:
2条回答
  • 2021-02-05 10:05

    How about something like this:

    HTML

    <input type="text" />
    
    <ul id="category1">
        <li>item1</li>
        <li>item2</li>
        <li>item3</li>
    </ul>
    <ul>
        <li>item27</li>
        <li>item28</li>
    </ul>
    

    JS

    $(function(){
    
        $('input[type="text"]').keyup(function(){
    
            var searchText = $(this).val();
    
            $('ul > li').each(function(){
    
                var currentLiText = $(this).text(),
                    showCurrentLi = currentLiText.indexOf(searchText) !== -1;
    
                $(this).toggle(showCurrentLi);
    
            });     
        });
    
    });
    

    http://jsfiddle.net/EFTZR/146/

    Another solution using filter(), which is mentioned below:

    $('input[type="text"]').keyup(function(){
    
        var that = this, $allListElements = $('ul > li');
    
        var $matchingListElements = $allListElements.filter(function(i, li){
            var listItemText = $(li).text().toUpperCase(), 
                searchText = that.value.toUpperCase();
            return ~listItemText.indexOf(searchText);
        });
    
        $allListElements.hide();
        $matchingListElements.show();
    
    });
    

    http://jsfiddle.net/EFTZR/441/

    0 讨论(0)
  • 2021-02-05 10:13

    You can do this with the filter method in jQuery:

    var valueToSearch = "item1"; // this one should come from the search box
    var allListItems = $("ul > li");
    var filteredItems = allListItems.filter(function(index) {
        var listItemValue = $(this).text();
        var hasText = listItemValue.indexOf(valueToSearch) > -1;
        return hasText;
    });
    

    Next, you can display the values in the filteredItems variable in a list or something like that, using a for loop.

    0 讨论(0)
提交回复
热议问题