«

»

JQuery to make a lazy filter (like iTunes)

This code is not mine, I’d link out to the source, but I’ve forgotten it. If you wrote this, thank you.


$('tbody tr').hover(function(){
$(this).find('td').addClass('hovered');
}, function(){
$(this).find('td').removeClass('hovered');
});

//default each row to visible
$('tbody tr').addClass('visible');

$('#filter').keyup(function(event) {
//if esc is pressed or nothing is entered
if (event.keyCode == 27 || $(this).val() == '') {
//if esc is pressed we want to clear the value of search box
$(this).val('');

//we want each row to be visible because if nothing
//is entered then all rows are matched.
$('tbody tr').removeClass('visible').show().addClass('visible');
}
//if there is text, lets filter
else {
filter('tbody tr', $(this).val());
}
});

//filter results based on query
function filter(selector, query) {
query =   $.trim(query); //trim white space
query = query.replace(/ /gi, '|'); //add OR for regex query

$(selector).each(function() {
($(this).text().search(new RegExp(query, "i")) < 0) ? $(this).hide().removeClass('visible') : $(this).show().addClass('visible');
});
}

Permanent link to this article: http://www.lukemacneil.com/2009/11/06/jquery-to-make-a-lazy-filter-like-itunes/

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>