jQuery Inline Search Plugin

This tiny yet powerful jquery plugin tutorial will teach you how to make an inline search with jquery. This can be applied to ANY elements in the DOM, table rows, table cells, spans within a div, every paragraph on a site, anything.

jquery plugin step 1. Create a new jquery method similar to below, basically what this is saying is to extend the jquery $ namespace with your function of search.

$.fn.<strong>search</strong> = function(searchElements) {
};

Step 2. The this keyword simply contains the currently selected elements, so later when we call $('input#inline-search').search(); input#inline-search is what is being passed to this. Followed of course by the keyup event.

$.fn.search = function(searchElements) {
  $(this).keyup(function(){
  });
};

Step 3. Store the search string using the .val(); method. searchElements which can be passed into our search(); method is simply what elements you will be searching in, this can be almost anything, examples might be 'table tr', 'table tr td', 'select option', 'table tr, select option' for multiple element searching! etc.

$.fn.search = function(searchElements) {
  $(this).keyup(function(){
    var searchString = $(this).val();
  });
};

Step 4. Now we are simply checking the length inputted to the search field, when nothing is entered we want to show all the elements. When something is being searched for we want to check if searchElements contains that string anywhere within the html it contains and then show it of it does.

$.fn.search = function(searchElements) {
  $(this).keyup(function(){
    var searchString = $(this).val();

    if (searchString.length &gt; 0){
      $(searchElements).hide();
      $(searchElements+':contains(' +searchString+ ')').show();
    }
    else {
      $(searchElements).show();
    }
  });

Final jquery plugin development code

$(document).ready(function(){
  $('input#inline-search').search('select option');
});
$.fn.search = function(searchElements) {
  $(this).keyup(function(){
    var searchString = $(this).val();

    if (searchString.length &gt; 0){
      $(searchElements).hide();
      $(searchElements+':contains(' +searchString+ ')').show();
    }
    else {
      $(searchElements).show();
    }
  });
};

Comments

Hi,

Thankyou so much for the example. I've used it in our project.

Here is a working example:

http://suneelgv.googlepages.com/jquerysearch

do you have an working example?

I do not understand how to start the inline search. If i define a input field with id inline-search, nothings happens. I think I have to initiate the functionality somehow, but I do not know how.

Cheers -- jErik

good