Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to create a filter list with JavaScript?
To create a filter list with JavaScript, the code is as follows −
Example
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
* {
box-sizing: border-box;
}
.searchInput {
width: 100%;
font-size: 16px;
padding: 12px 20px 12px 40px;
border: 2px solid grey;
margin-bottom: 12px;
}
.animalUL {
list-style-type: none;
padding: 0;
margin: 0;
}
.animalUL li a {
border-top: 1px solid rgb(0, 0, 0);
margin-top: -1px;
background-color: #f6f6f6;
padding: 12px;
text-decoration: none;
font-size: 18px;
color: black;
display: block;
}
.animalUL li a:hover:not(.header) {
background-color: #eee;
}
</style>
</head>
<body>
<h1>Filter list example</h1>
<input type="text" class="searchInput" onkeyup="filterFunction()" placeholder="Search for animals" title="Type in a name"/>
<ul class="animalUL">
<li><a href="#">Cat</a></li>
<li><a href="#">Cheetah</a></li>
<li><a href="#">Dog</a></li>
<li><a href="#">Giraffe</a></li>
<li><a href="#">Lion</a></li>
<li><a href="#">Leopard</a></li>
<li><a href="#">llama</a></li>
</ul>
<script>
function filterFunction() {
var input, filter, ul, li, a, i, value;
input = document.querySelector(".searchInput");
filter = input.value.toUpperCase();
ul = document.querySelector(".animalUL");
li = ul.getElementsByTagName("li");
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("a")[0];
value = a.textContent || a.innerText;
if (value.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
}
}
</script>
</body>
</html>
Output
The above code will produce the following output −

On typing something in the search field −

Advertisements