Filter list items with jQuery


Sometimes while working with list items or contents, we need to filter out the list items or contents for some matching records. We can implement this using jQuery with ease. Here is a little jQuery code snippet to implement local search.


  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
  <script type="text/javascript">
  $(document).ready(function(e) {
    $('#search').keyup(function(){
    var val = $(this).val();
    $(".list").find('li').each(function(){  
      ($(this).text().search(new RegExp(val, "i")) === -1) 
             ? $(this).hide() : $(this).show();
      });  
    });
  });
  </script>


  <input type="text" id="search" />
  <ul class="list">
    <li>Australia</li>
    <li>Bangladesh</li>
    <li>India</li>
    <li>New Zealand</li>
    <li>Pakistan>
    <li>South Africa</li>
    <li>Sri Lanka</li>
    <li>West Indies</li>
  </ul>

Here is a working demo

  • Australia
  • Bangladesh
  • India
  • New Zealand
  • Pakistan
  • South Africa
  • Sri Lanka
  • West Indies

Filter list items with jQuery Filter list items with jQuery Reviewed by Altaf Hussain on 12:30 AM Rating: 5

No comments:

Altaf Web. Powered by Blogger.