Is there a way to implement this script for options instead of buttons? The goal is to filter the HTML section, but it seems to not work with <option>
tags. Instead of displaying the all class, it shows nothing.
CSS
.show {
display: block;
}
.filterDiv {
display: none;
}
This is the default filter section set to show all items.
<div class="col-lg-6 col-sm-6 col-12" id="myBtnContainer">
<div class="release-filter justify-content-end d-flex">
<div class="filter-title">
<select name="year">
<option class="btn active" value="" onclick="filterSelection('all')" disabled selected>Filter By Year</option>
<option class="btn" value="2023" onclick="filterSelection('2023')">2023</option>
<option class="btn" value="2022" onclick="filterSelection('2022')">2022</option>
<option class="btn" value="2021" onclick="filterSelection('2021')">2021</option>
<option class="btn" value="2020" onclick="filterSelection('2020')">2020</option>
</select>
</div>
</div>
</div>
Although this item should be filtered, it currently does not work as expected and does not display anything.
<div class="col-xl-6 col-lg-6 col-12 filterDiv 2023">
<div class="collection-release">
</div>
</div>
Javascript
filterSelection("all")
function filterSelection(c) {
var x, i;
x = document.getElementsByClassName("filterDiv");
if (c == "all") c = "";
// Add the "show" class (display:block) to the filtered elements, and remove the "show" class from the elements that are not selected
for (i = 0; i < x.length; i++) {
w3RemoveClass(x[i], "show");
if (x[i].className.indexOf(c) > -1) w3AddClass(x[i], "show");
}
}
// Show filtered elements
function w3AddClass(element, name) {
var i, arr1, arr2;
arr1 = element.className.split(" ");
arr2 = name.split(" ");
for (i = 0; i \< arr2.length; i++) {
if (arr1.indexOf(arr2\[i\]) == -1) {
element.className += " " + arr2\[i\];
}
}
}
// Hide elements that are not selected
function w3RemoveClass(element, name) {
var i, arr1, arr2;
arr1 = element.className.split(" ");
arr2 = name.split(" ");
for (i = 0; i \< arr2.length; i++) {
while (arr1.indexOf(arr2\[i\]) \> -1) {
arr1.splice(arr1.indexOf(arr2\[i\]), 1);
}
}
element.className = arr1.join(" ");
}
// Add active class to the current control button (highlight it)
var btnContainer = document.getElementById("myBtnContainer");
var btns = btnContainer.getElementsByClassName("btn");
for (var i = 0; i \< btns.length; i++) {
btns\[i\].addEventListener("click", function() {
var current = document.getElementsByClassName("active");
current\[0\].className = current\[0\].className.replace(" active", "");
this.className += " active";
});
}
\</script\>