Someday before I faced a question of live text search using jQuery means how to search a text with in a DOM element using jQuery. Live search using jquery script can be integrated easily on any page where you are listing products, user profiles, news, blog posts & any ordered or unordered lists etc.
We can implement this script on any type of selector. Like first you fill up the friend list in your page and now you want to search your friend by his name in text box. As you input the character in the text box, search will be live and result would be filtered accordingly in respect of input characters in case insensitive manner.
View Demo
Live text search using jQuery
Script
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | $(document).ready(function(){ $("#txtSearch").keyup(function(){ var str = $(this).val(); $(".friends .friend").each(function(index){ if($(this).data("name") !== undefined){ if(!$(this).data("name").match(new RegExp(str, "i"))){ $(this).fadeOut("fast"); }else{ $(this).fadeIn("slow"); } } }); }); }); |
Here I am using inputbox keyup event to search on every character and checking the input value with the attribute data-name using regular expression. If match, show the friend with fadeIn effect else hide with fadeout effect.
We can use whatever attribute or data attribute name here according to that we need to change the script and also we can change the effect of showing and hiding also.
HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | <input type="text" id="txtSearch" name="txtSearch" placeholder="search your friends here" /> <div class="friends"> <div class="friend fl" data-name="Kamal Agarwal"> <div class="name fl"><a href="#">Vaibhav Ladage</a></div> </div> <div class="friend fl" data-name="Ashutosh"> <div class="name fl"><a href="#">Ashutosh</a></div> </div> <div class="friend fl" data-name="Amit Saunkhiya"> <div class="name fl"><a href="#">Amit Saunkhiya</a></div> </div> <div class="friend fl" data-name="Steve Jobs"> <div class="name fl"><a href="#">Steve Jobs</a></div> </div> <div class="friend fl" data-name="Bill Gates"> <div class="name fl"><a href="#">Bill Gates</a></div> </div> <div class="friend fl" data-name="Sandeep Sharma"> <div class="name fl"><a href="#">Sandeep Sharma</a></div> </div> <div class="friend fl" data-name="Priya Aggarwal"> <div class="name fl"><a href="#">Priya Aggarwal</a></div> </div> <div class="friend fl" data-name="Pramod Gupta"> <div class="name fl"><a href="#">Pramod Gupta</a></div> </div> <div class="friend fl" data-name="Yogesh panday"> <div class="name fl"><a href="#">Yogesh panday</a></div> </div> <div class="friend fl" data-name="John Robert"> <div class="name fl"><a href="#">John Robert</a></div> </div> <div class="friend fl" data-name="David harlay"> <div class="name fl"><a href="#">David harlay</a></div> </div> </div> </div> |
View Demo
Please don’t forget to share the post. Comments and feedbacks are always welcome.