Friday, April 24, 2009

Filter Lists With JQuery

Here's a little snippet that will filter a list as the user types as well as bold the search expression within the list.


$("#searchMyProjects").keyup(function() {
var filter = $(this).val(), count = 0;
$("span.projectSelectionName").each(function() {
if ($(this).text().search(new RegExp(filter, "i")) < 0) {
$(this).parent().parent().hide();
$(this).hide();
} else {
$(this).parent().parent().show();
$(this).html($(this).text().replace(new RegExp(filter, "i"), "<b>" + filter + "</b>"));
$(this).show();
count++;
}
});
$("#filterCount").text(count);
});


The filter expression s updated with <b> tags to highlight the search expression within the text. You can use whatever styling you want, of course.

Enjoy.

No comments:

Post a Comment