Search Anything with JQuery

Here’s a quick set of functions to search a table, search a list, search paragraphs of text, or search just about anything on a page with JQuery.

The key to making this work effectively is adding the datasearch property to the items being searched and ensuring that your JQuery selector is unique to the set of items you want to search.

function runQuickSearch(searchBox, searchTarget){
    var search = jQuery(searchBox).val().toLowerCase();
    var found = false;
    jQuery(searchTarget).each(function() {
      found = false;
      searchValue = jQuery(this).data('search').toLowerCase();
      if (searchValue.indexOf(search) >= 0 || search.len == 0 ) {
        found = true;
      }
      if (found) { jQuery(this).show(); } else { jQuery(this).hide(); }
    });
  }
                              
  function quickSearch(searchBox, searchTarget){
    jQuery(searchBox).click(function() {
      runQuickSearch(searchBox, searchTarget);
    });

    jQuery(searchBox).keyup(function() {
      runQuickSearch(searchBox, searchTarget);
    });
  }
                              

How to link a search box with the items to be searched

The code below will link the text box #search with the rows of a table with the id #customers. To ensure that the headers don’t get removed, ensure your data rows are inside a <tbody> tag.

jQuery(document).ready(function(){
   quickSearch('#search','#customers tbody tr');
});

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.