Filter list based on user input with jQuery
I have a list of songs and I want users to be able to filter them by entering a text box. Here's what I'm doing now:
$("#filter_song_list").keyup(function() {
var filter = new RegExp($(this).val(), "i");
$("ul.song_list a").each(function(){
if (!$(this).text().match(filter)) {
$(this).hide();
} else {
$(this).show();
}
});
});
- Is this the correct approach?
- Since I am interpreting user input as a regex, it cannot search for songs with (say) a period in the title without its first output ("."). How can I fix this while keeping the search case insensitive?
source to share
Choose your regex before executing it :
var pattern = $(this).val().replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1');
var filter = new RegExp(pattern , "i");
However, you are just doing a case-insensitive search of the string within the string. You don't need regular expressions for this. @ mkoryak's answer is more suitable for you IMO.
I would say jQuery's built-in contains
psuedo selector was perfect for you, but it's case sensitive.
source to share
First of all, make a cached link to your elements to speed things up:
var cache = $("ul.song_list a");
Then do a simple string match using jQuery function filter()
and hide()
matched elements:
cache.filter(function ()
{
return $(this).text().toLower().indexOf( <value from input> ) < 1;
}).hide();
Last snippet of code:
$(function ()
{
var cache = $("ul.song_list a");
$("#filter_song_list").keyup(function ()
{
var val = $(this).val();
cache.filter(function ()
{
return $(this).text().toLower().indexOf(val) < 1;
})
.hide();
});
});
source to share