Welcome to a beginner’s tutorial on how to filter or search a list in Javascript. So you have a long list of products, users, inventory, or just about any item for that matter. How do we improve the interface and add a search filter to that massive list?
Yep, that is searching using client-side Javascript, and not throwing the search request back to the server. Save the server’s resources, and use the users’ devices. Thankfully, it isn’t that difficult. Read on to find out how!
TABLE OF CONTENTS
JAVASCRIPT FILTER LIST
All right, let us get started with creating a simple HTML list and adding a Javascript search box to it.
LIST FILTER DEMO
- Apple
- Apricots
- Avocado
- Banana
- Blackberries
- Blueberries
- Cherries
- Coconut
- Cranberries
- Durian
- Elderberries
- Grapefruit
- Grapes
- Guava
- Honeydew
- Jackfruit
- Longan
- Loquat
- Mango
- Orange
- Papaya
- Pear
- Pineapple
- Strawberries
- Watermelon
STEP 1) THE HTML
<!-- (A) SEARCH BOX -->
<input type="text" id="the-filter" placeholder="Search For...">
<!-- (B) LIST OF ITEMS -->
<ul id="the-list">
<li>Apple</li>
<li>Apricots</li>
<li>Avocado</li>
<li>Banana</li>
<li>Blackberries</li>
<li>Blueberries</li>
<li>Cherries</li>
<li>Coconut</li>
<li>Cranberries</li>
<li>Durian</li>
<li>Elderberries</li>
<li>Grapefruit</li>
<li>Grapes</li>
<li>Guava</li>
<li>Honeydew</li>
<li>Jackfruit</li>
<li>Longan</li>
<li>Loquat</li>
<li>Mango</li>
<li>Orange</li>
<li>Papaya</li>
<li>Pear</li>
<li>Pineapple</li>
<li>Strawberries</li>
<li>Watermelon</li>
</ul>
The HTML is very straightforward, and there are only 2 parts to it:
<input type="text" id="the-filter">
The search box.<ul id="the-list">
List of items.
STEP 2) THE CSS
/* (A) SEARCH BOX */
#the-filter {
width: 100%;
margin-bottom: 15px;
padding: 10px;
}
/* (B) LIST */
#the-list {
list-style: none;
margin: 0;
padding: 0;
}
#the-list li {
padding: 10px;
border-bottom: 2px solid #ffe9e9;
}
#the-list li:hover { background: #fffed6; }
#the-list li.hide { display: none; }
These are just some cosmetics, basically styling the unordered list #the-list
to look nicer with stripes and stuff. The only thing to take note of is the #the-list li.hide
class – We will use this one to hide list items that don’t match the search term later.
STEP 3) THE JAVASCRIPT
window.addEventListener("load", () => {
// (A) GET HTML ELEMENTS
var filter = document.getElementById("the-filter"), // search box
list = document.querySelectorAll("#the-list li"); // all list items
// (B) ATTACH KEY UP LISTENER TO SEARCH BOX
filter.onkeyup = () => {
// (B1) GET CURRENT SEARCH TERM
let search = filter.value.toLowerCase();
// (B2) LOOP THROUGH LIST ITEMS - ONLY SHOW THOSE THAT MATCH SEARCH
for (let i of list) {
let item = i.innerHTML.toLowerCase();
if (item.indexOf(search) == -1) { i.classList.add("hide"); }
else { i.classList.remove("hide"); }
}
};
});
Sorry to the folks who are expecting to see hundreds of lines of code… Because this is all we need. This should be very straightforward as well, just follow through step-by-step:
- (A) Wait for the page to be fully loaded first, then get the HTML search box and all the list items.
- (B) Attach an
onkeyup
listener to the search box, this will be fired whenever the user presses a key in the search box. - (B1 & B2) Get the current search term, then loop through all the list items. Hide the items that don’t match the search term using the
.hide
CSS class, show the items that match by removing the.hide
CSS class.
The end. If you want a case-sensitive search, remove both .toLowerCase()
from the script.
AJAX FILTER LIST
What if we want to use AJAX to fetch raw data from the server? How do we generate a list and attach a filter to it? Here is a small modification to the above example.
STEP 1) HTML PAGE
<!-- (A) SEARCH BOX -->
<input type="text" id="the-filter" placeholder="Search For...">
<!-- (B) LIST OF ITEMS -->
<ul id="the-list"></ul>
Yep, it’s the same as above, except that the list of items is empty now – We will load it via AJAX instead.
STEP 2) SERVER-SIDE DATA
["Apple","Apricots","Avocado","Basnana","Blackberries","Blueberries","Cherries","Coconut",
"Cranberries","Durian","Elderberries","Grapefruit","Grapes","Guava","Honeydew","Jackfruit",
"Longan","Loquat","Mango","Orange","Papaya","Pear","Pineapple","Strawberries","Watermelon"]
This is the part where you generate the list of items on the server side. That could be extracting data from the database, reading from a file, or getting raw data from somewhere else… Not going into the details here since it is different for everyone. I am just going to leave this simple list of JSON-encoded fruits as an example.
STEP 3) JAVASCRIPT
window.addEventListener("load", () => {
// (A) GET DATA FROM SERVER VIA AJAX FETCH
fetch("e2-server.json")
.then(res => res.json())
.then(data => {
// (B) GET HTML ELEMENTS
let filter = document.getElementById("the-filter"), // search box
list = document.getElementById("the-list"); // list item wrapper
// (C) DRAW HTML LIST
for (let i of data) {
let li = document.createElement("li");
li.innerHTML = i;
list.appendChild(li);
}
// (D) SAME AS BEFORE
list = document.querySelectorAll("#the-list li");
filter.onkeyup = () => {
// (D1) GET CURRENT SEARCH TERM
let search = filter.value.toLowerCase();
// (D2) LOOP THROUGH LIST ITEMS - ONLY SHOW THOSE THAT MATCH SEARCH
for (let i of list) {
let item = i.innerHTML.toLowerCase();
if (item.indexOf(search) == -1) { i.classList.add("hide"); }
else { i.classList.remove("hide"); }
}
};
});
});
The Javascript remains pretty much the same as well.
- Load the data from the server using
fetch()
. - Looks familiar? Same – We get the search box and empty list.
- Generate the list of items from the data.
- Get all the generated list items, this part is entirely the same as above.
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
EXAMPLE CODE DOWNLOAD
Click here for the source code. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
SORRY FOR THE ADS...
But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.
Buy Me A Coffee Code Boxx eBooks
EXTRA BITS & LINKS
That’s all for this tutorial, and here is a small section on some extras and links that may be useful to you.
LINKS & REFERENCES
- Simple AJAX Examples – Code Boxx
- Javascript DOM – MDN
COMPATIBILITY CHECKS
- Fetch – CanIUse
- Arrow Function – CanIUse
This search filter will work on all modern browsers.
TUTORIAL VIDEO
INFOGRAPHIC CHEAT SHEET
THE END
Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!
Any way to do this w/o showing the complete list – just the results?
1) Start with an empty <ul>
2) Define the data in a Javascript array instead.
3) Modify the Javascript to append <li> into the empty list for the matched results.
This was exactly what I needed. We had a list of veterans that was provided in a plain “ format, and this solution was easy to integrate without any need for list conversion.
Much appreciated, and great work!
Hello Toh,
I walked through your project “3 Simple Steps To Filter/Search a List in Javascript”, it is really nice, appreciated.
I am passing very hard time to figure how to go for wild search in search box from a selected field in combo box which I covered in VB DotNet.
The scenario is
a) The random search records display in Listbox, then click/select the specific record, will display in respective input/text boxes for further edit the selected record.
In PHP, things are little different. What’s your suggestion? Can you refer for good project/example/s, so that I can come up with some reasonable solution for my problem?
How I can send the screen shot of my project? Then you could be able to get the good idea.
Thanks .
Regards.
Shamsul Arifin
AJAX is your best friend –
1) AJAX load search results into list box.
2) Click on record > AJAX load form.
As for the rest, sorry, I don’t give free project consultations. -_-
https://code-boxx.com/faq/#help “I don’t work for free”