জাভাস্ক্রিপ্ট দিয়ে ফিল্টার লিস্ট তৈরির কোড।
উদাহরণ
<!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 = document.querySelector(".searchInput");
var filter = input.value.toUpperCase();
var ul = document.querySelector(".animalUL");
var li = ul.getElementsByTagName("li");
for (var i = 0; i < li.length; i++) {
var a = li[i].getElementsByTagName("a")[0];
var value = a.textContent || a.innerText;
if (value.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
}
}
</script>
</body> </html>
আউটপুট
সার্চ বক্সে টাইপ করলে লিস্ট রিয়েল-টাইমে ফিল্টার হবে। "cat" টাইপ করলে "Cat", "Cheetah" দেখাবে।
ব্যাখ্যা
onkeyupইভেন্টে ফিল্টার ফাংশন কল হয়toUpperCase()দিয়ে কেস-ইনসেনসিটিভ ম্যাচindexOf() > -1সাবস্ট্রিং ম্যাচ চেক করেstyle.display = "none"দিয়ে হাইড,""দিয়ে শো
মডার্ন উন্নতি (ES6+)
const filterFunction = () => {
const filter = document.querySelector(".searchInput").value.toLowerCase();
document.querySelectorAll(".animalUL li").forEach(li => {
const text = li.textContent.toLowerCase();
li.style.display = text.includes(filter) ? "" : "none";
});
};
পারফরম্যান্স টিপ
- বড় লিস্টের জন্য
debounceব্যবহার করুন (৩০০মিসি विलম্ব) - ভার্চুয়াল স্ক্রোলিং বা পেজিনেশন বিবেচনা করুন
- React/Vue-এ state দিয়ে ফিল্টারড লিস্ট রেন্ডার করুন