jQuery: Search text in elements and display only elements that matches the text

It displays only the elements that contains the text we are searching for.

// Run the code on every text entered
$('#text').keyup(function () {
// Get the text input value
var inputval = $(this).val();
// remove the foo class from foo class elements
$("#dad li.foo").removeClass("foo");
// Filter through all list element (see http://stackoverflow.com/a/7569871/2131693) and add the foo class to mark the list elements we are interested in
var x = $("#dad li").filter(function () {
return $(this).text().substr(0, inputval.length) === inputval;
// show the foo class elements
$("#dad li.foo").show("slow");
// hide the non foo class elements that we are not interested in
$("#dad li").not('.foo').hide('slow');

See it in action on Fiddle


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s