How to implement a search function using javascript or jquery

here I am writing code where all the names of people come from the Facebook API. and it is displayed on the lightbox. now I want to implement a search function using javasciprt / jquery. Can you help me how to implement the search function?

<div> <input type="text" id="search-criteria"/> <input type="button" id="search" value="search" onClick="tes();"/> </div> <fieldset> <legend>Invite Facebook Friend</legend> <div class="fbbox"> <img src="images/User.png" class="fbimg" /> <div class="fix"><label for="check-2" class="left"> James </label></div> <input type="checkbox" name="fb" id="check-1" value="action" class="leftcx"/> </div> <div class="fbbox"> <img src="images/User.png" class="fbimg" /> <div class="fix"><label for="check-2" class="left">Alan </label></div> <input type="checkbox" name="fb" id="check-2" value="comedy" class="leftcx"/> </div> <div class="fbbox"> <img src="images/User.png" class="fbimg" /> <div class="fix"><label for="check-3" class="left"> Mathew </label></div> <input type="checkbox" name="fb" id="check-3" value="epic" class="leftcx"/> </div> 

Image

+6
source share
4 answers
 $("#search-criteria").on("keyup", function() { var g = $(this).val(); $(".fbbox .fix label").each( function() { var s = $(this).text(); if (s.indexOf(g)!=-1) { $(this).parent().parent().show(); } else { $(this).parent().parent().hide(); } }); });​ 

Working script

or better way:

 $("#search-criteria").on("keyup", function() { var g = $(this).val().toLowerCase(); $(".fbbox .fix label").each(function() { var s = $(this).text().toLowerCase(); $(this).closest('.fbbox')[ s.indexOf(g) !== -1 ? 'show' : 'hide' ](); }); });​ 

Working script

+15
source

Perhaps use the indexOf method:

 var text ="some name"; var search = "some"; if (text.indexOf(search)!=-1) { // do someting with found item } 
0
source

Use jQuery

 ​ $(document).ready(function(){ var search = $("#search-criteria"); var items = $(".fbbox"); $("#search").on("click", function(e){ var v = search.val().toLowerCase(); if(v == "") { items.show(); return; } $.each(items, function(){ var it = $(this); var lb = it.find("label").text().toLowerCase(); if(lb.indexOf(v) == -1) it.hide(); }); }); });​ 

Demo: http://jsfiddle.net/C3PEc/2/

0
source

You can use the regular expression instead of indexOf , because it may not work in IE7 / IE8 and using the regular expression, you can also use the "i" modifier to make the search case insensitive.

thanks

0
source

All Articles