Search code examples
jquerysearchfindjquery-filter

jQuery - Search as you type on page just like cpanel search


I am looking for a functionality just like cpanel search. Where as you type in search box, the similar content stays and rest disappears. Example

<div>hello</div>
<div>world</div>
<div>good</div>
<div>bad</div>
<input type="text" name="search">

Now as I start typing "he". Only hello display and rest of the divs goes to display:none;

Is it possible? People who have seen Cpanel search box, knows what I am asking. I have been looking around for this but could not find anything similar to it. Thanks in advance.


Solution

  • Sure pretty simple, just use the keyup event and toggle the <div>'s accordingly

    jsFiddle

    HTML

    <div id="example">
      <div>hello</div>
      <div>world</div>
      <div>good</div>
      <div>bad</div>
    </div>
    <input type="text" name="search" id="search">
    

    JS

    $(function(){
        $('#search').keyup(function(event){
            var keyCode = event.which; // check which key was pressed
            var term = $(this).val();
            $('#example').children().hide(); // hide all
            $('#example').children(':Contains("' + term + '")').show(); // toggle based on term
        });
     });​
    
     $.expr[':'].Contains = function(a, i, m) { 
        return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase()) >= 0; 
     };