JS Snippets: Filter a List with jQuery and JavaScript Regular Expression

May 19, 2013 9:21 pm Leave your thoughts

Have you ever had to present a list then filter based on the keywords that the user entered? I have and it was pretty simple to do, however it did require a bit of research. Since I’ve done it I might as well share it with you all. The technique involves the use of a couple in-built jQuery functions and javascript regular expression matching. So basically our aim in this exercise is to show only the list item that contains the correct keyword, basically hiding those list items that do not have the matching keyword.

So, let’s create our list of images with simple UL listing. The images thumbnails are taken from with permissions.

Basically the above is just a simple list of images, with a search box. What we want is that on each keystrokes, a javascript action is executed to hide the images that doesn’t match the keyword. So have a look at the code snippets below.

The codes above save the value from the textbox in a variable in the local scope filterValue. Then it proceed to make sure that every single images are displayed by default.

At the core of the logic is the matching function. The portion of the code finds all the li elements that do not match the filterValue, this is done by the .not selector fed with custom matching function. Our custom matching function basically takes the current contains of the li into a HTML string and uses the standard JavaScript “match” function and RegExp object to filter by the filterValue.

Lastly, once all the items that doesn’t match the keyword is found, we hide all of them, leaving only the matching images behind. Have a look at the JsFiddle below for a quick demonstration. If you start typing in the word flower, the other images that doesn’t match that will be hidden.

Take this piece of code with a grain of salt, this is a  very quick solution that I came up in about 30 minutes. If you find a better way, do leave your suggestions in the comments for others to read :)

Tags: , ,

Categorised in: ,