Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show divs based on text search

I have a text input search that is supposed to filter divs based on the title of the div. Here is the code that is not working:

$('.contact-name').each(function(){
  var txt = $('#search-criteria').val();
  $('this').find(txt).show()      
});

What am I doing wrong?

EDIT: To clarify the variable txt is what the user has typed in the input field. An example would be if txt was Cha I would want this row to show:

<div class="contact-name"><h3><a href="##">Charles Smith</a></h3></div>
like image 750
Josh Scott Avatar asked Mar 01 '12 03:03

Josh Scott


2 Answers

try this

var txt = $('#search-criteria').val();
$('.contact-name:contains("'+txt+'")').show();

documentation for :contains() Selector

fiddle example : http://jsfiddle.net/WBvTj/2/

UPDATE CASE INSENSITIVE:

var txt = $('#search-criteria').val();
$('.contact-name').each(function(){
   if($(this).text().toUpperCase().indexOf(txt.toUpperCase()) != -1){
       $(this).show();
   }
});

fiddle Example : http://jsfiddle.net/WBvTj/4/

like image 163
dku.rajkumar Avatar answered Oct 03 '22 04:10

dku.rajkumar


The following should be case-insensitive, and match only on text in first a href in the div:

var pattern = "/" + $('#search-criteria').val() + "/i";
$('.contact-name').filter(function() {
    return $(this 'a:first-child').html().match(pattern).length > 0;
}).show();

filter gives you a list of elements that return true from that function in it to apply show() to.
The return in the filter function can be read as: "for the first anchor element in this element, take the contents, match it against the pattern, and if the resulting array contains 1 or more results, return true".

The "i" on the end of the pattern is what gets you case-insensitive matching.

like image 26
Patches Avatar answered Oct 03 '22 06:10

Patches