سؤال

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.

هل كانت مفيدة؟

المحلول

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; 
 };

نصائح أخرى

Yeah it's possible.

Here's my fiddle: http://jsfiddle.net/HQFQ5/2/

This is the function that makes it work:

$('input').bind('keyup',function(){
  var selfVal = $(this).val()
  var compareDivs = $('div');
  compareDivs.each(function(){
     var divVal = $(this).text().toString();
     if (divVal.indexOf(selfVal)<0)
         $(this).fadeOut();
     else
         $(this).fadeIn();
  });
});​
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top