how to implement Search function using Javascript or jquery
56,493
Solution 1
$("#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();
}
});
});
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' ]();
});
});
Solution 2
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/
Author by
Rushikesh jogle
Updated on July 22, 2022Comments
-
Rushikesh jogle almost 2 years
here i write code where all persons names comes from Facebook API . and it is showing on lightbox. now i want to implement search functionality using javasciprt/jquery . Can you help me how should i implement 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>
-
Florian Margaine over 11 yearsSo... use jQuery just because of
indexOf
, which you don't need jQuery for? -
Andy Ecca over 11 years@FlorianMargaine, use jquery for events and each function.
-
Muhammad Talha Akbar over 11 yearssorry man the code i gave you, don't search by clicking search button but do it automatically!
-
Rushikesh jogle over 11 years@Andy Thank you for help :)
-
Mottie over 11 years+1 Nice answer, but I would also make it case insensitive:
var g = $(this).val().toLowerCase();
andvar s = $(this).text().toLowerCase()
- updated demo -
Mottie over 11 yearsThis breaks when you search for "fb 1" then change to "fb 3"... it won't unhide "fb 3". Change this:
if (lb.indexOf(v) == -1) { it.hide(); } else { it.show(); }
-
Muhammad Talha Akbar over 11 years@Mottie I add the link of your fiddle also ;)