Search/ filter list of UI LI data using simple Jquery with filter() method

Html+Css
Dec 04 2018
52 Views

Search/ filter list of UI LI data using simple Jquery with filter() method

Introduction

I want to share you a simple list filter using Jquery and UI LI list items. In this post I used "filter" method jquery. 

Filter
The filter() method returns elements that match. You need to specify a criteria to match elements. Elements that do not match the criteria are removed from the selection, and those that match will be returned. I have used this method to filter list of data when keyup. Please refer http://api.jquery.com/filter/ for more information.

Html

<input type="text" />

<ul id="category">
    <li>Apple </li>
    <li>Banana </li>
    <li>Blackberry</li>
    <li>Custard apple</li>
</ul>

Jquery

$('input[type="text"]').keyup(function(){
    
    var that = this;
    var all_list = $('ul > li');

    var matching_list = all_list.filter(function(i, li){
        var list_item_text = $(li).text().toUpperCase();
        var search_text = that.value.toUpperCase();
        return ~list_item_text.indexOf(search_text);
    });
    
    all_list.hide();
    matching_list.show();
    
});

Html - Multiple list
If you have multiple lists, this code will work.

<input type="text" />

<ul id="category1">
    <li>Apple </li>
    <li>Banana </li>
    <li>Blackberry</li>
    <li>Custard apple</li>
</ul>
<ul>
    <li>Amaranth</li>
    <li>Arugula</li>
    <li>Beet</li>
    <li>Cabbage</li>
</ul>

Conclusion
For simple and short list, you can implement filter using this post. 

Leave a Reply