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;
}).addClass("foo");
// 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