I needed a simple filter system on a unordered list. The goal is to filter 'realtime' based on what a user is typing. I came up with the following, if you have any suggestions and/or performance tips feel free to drop a line!
The HTML:
The blog software is messing with the HTML, for a working example with ungarbled code. Look at the bottom of this post.
</p><div>
<input name="filter" id="search_filter" type="text">
</div><div id="titles">
<ul>
<li><a href="http://blog.dynom.nl/path/to/item/1">Item 1</a></li>
<li><a href="http://blog.dynom.nl/path/to/item/2">Item 2</a></li>
<li><a href="http://blog.dynom.nl/path/to/item/3">Item 3</a></li>
</ul>
</div>
The Javascript
var My = {}
My.List = {
Filter : function (inputSelector, listSelector) {
// Sanity check
var inp, rgx = new RegExp(), titles = $(listSelector), keys;
if (titles.length === 0) {
return false;
}
// The list with keys to skip (esc, arrows, return, etc)
// 8 is backspace, you might want to remove that for better usability
keys = [ 13, 27, 32, 37, 38, 39, 40, 8 ];
// binding keyup to the unordered list
$(inputSelector).bind('keyup', function (e) {
if (jQuery.inArray(e.keyCode, keys) >= 0) {
return false;
}
// Building the regex from our user input, 'inp' should be escaped
inp = $(this).attr('value');
rgx.compile(inp, 'im');
titles.each(function () {
if (rgx.source !== '' && !rgx.test($(this).html())) {
$(this).parent('li').hide();
} else {
$(this).parent('li').show();
}
});
});
}
};
// When the DOM is ready
$(document).ready(function () {
// Attach the filter to our input and list
My.List.Filter('input#search_filter', '#titles>ul>li>a');
});
Working example
Visit http://dynom.nl/jquery/list.php for a working example.