Search code examples
javascriptjquerysearchfiltershow-hide

Filter links with the help of text input search and hide non matching


i got a problem i am not very familar with jquery effects and functions. I wanted a simple filter function where you can filter links which are categories on a page in different but same build containers. Code Follows:

The Html Containers with the links which i want to filter and set to display none if dont match:

<div class="col-sm-3 py-4">
   <h4 class="text-white" id="hideOnFilter">Generatoren und Bilderupload</h4>
   <nav class="nav flex-column" id="filterholder">
      <a class="nav-link text-white catlink" href="#" title="Cat 1 description" id="filterelement">Cat 1</a>
      <a class="nav-link text-white catlink" href="#" title="Cat 2 description" id="filterelement">Cat 2</a>
      <a class="nav-link text-white catlink" href="#" title="Cat 3 description" id="filterelement">Cat 3</a>
      <a class="nav-link text-white catlink" href="#" title="Cat 4 description" id="filterelement">Cat 4</a>        
   </nav>
</div>

These containers above are placed six times on page but always the same class id and structure.

The JQuery Part to filter the links i wrote since so far:

 $('.search').keyup(function(){
          var searchcatquery = $(this).val();
          //alert(searchcatquery); 
          //Filter and hide links which dont match to search input? 
          return false;
 });

Solution

  • Try this approach using jquery filter

       $('.search').keyup(function(){
          var searchcatquery = $(this).val().toLowerCase(); //convert to lowercase     
    
          $(".catlink").show().filter(function(){
             return $(this).text().toLowerCase().indexOf( searchcatquery ) == -1 //filter all those who doesn't have searchcatquery as substring
          }).hide(); //hide filtered values
    
          return false;
        });
    

    Note

    • Either don't keep any id for an element or keep distinctive id for every element on an HTML page. ids should not be duplicated.
    • Logic given above doesn't use id attribute for filtering.