HTML filtering using the <select> element

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\>

Answer №1

I've made some changes to the code so that when a user selects a year, only the corresponding div for that year will be shown on the screen while the others are hidden. I hope this adjustment is helpful.

var selectYear = document.getElementById('yearSelect');
 selectYear.onchange = (event) => { //capture changes in selected options.
     var chosenYear = event.target.value; // get value of selected option.

  var elements, index;
  elements = document.getElementsByClassName("filterDiv");
  if (chosenYear == "all") chosenYear = "";
  
  for (index = 0; index < elements.length; index++) {
    w3RemoveClass(elements[index], "show");
    if (elements[index].classList.contains(chosenYear)) w3AddClass(elements[index], "show");
  }
}

function w3AddClass(element, className) {
     element.classList.add(className);
}

function w3RemoveClass(element, className) {
   element.classList.remove(className);
}

var buttonsContainer = document.getElementById("myBtnContainer");
var filterButtons = buttonsContainer.getElementsByClassName("btn");
for (var i = 0; i < filterButtons.length; i++) {
   filterButtons[i].addEventListener("click", function() {
   var currentActive = document.getElementsByClassName("active");
   currentActive[0].className = currentActive[0].className.replace(" active", "");
   this.className += " active";
   });
}
.show {
  display: block !important; 
}
.filterDiv {
  display: none;
}
<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" id="yearSelect">
                    <option class="btn active" value="" onclick="filterSelection('all')" disabled selected>Filter By Year</option>
                    <option class="btn" value="2023">2023</option>
                    <option class="btn" value="2022">2022</option>
                    <option class="btn" value="2021">2021</option>
                    <option class="btn" value="2020">2020</option>
                  </select>
            </div>
    </div>
</div>

<div class="col-xl-6 col-lg-6 col-12 show filterDiv 2023">
    <div class="collection-release">
    Div for 2023
    </div>
</div>
<div class="col-xl-6 col-lg-6 col-12 show filterDiv 2022">
    <div class="collection-release">
    Div for 2022
    </div>
</div>
<div class="col-xl-6 col-lg-6 col-12 show filterDiv 2021">
    <div class="collection-release">
    Div for 2021
    </div>
</div>
<div class="col-xl-6 col-lg-6 col-12 show filterDiv 2020">
    <div class="collection-release">
    Div for 2020
    </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The NodeJS req.query is providing inaccurate information

When I send a JSON from the Client-Side to a NodeJS Server, it looks like this: $.ajax({ type: "POST", dataType: "jsonp", url: "www.xyz.com/save", data: { designation: "Software Developer", skills: [ "", "ASP.NET", "P ...

Can we limit the number of items to just two per row in a grid with two columns?

I'm currently facing issues with aligning items within a two-column grid. When looking at this image, you'll notice that the alignment is off. Specifically, 'Example 3' does not align properly with 'Example 4'. This seems to b ...

Error message: AngularJS Jasmine spyOn: number has no functionality

I am encountering difficulties while attempting to execute a test that utilizes a mockup for a service call (retrieving location data from a web SQL database). Below is the controller code: .controller('LocationDetailCtrl', function ($scope, $s ...

Responsive images in CSS3/HTML5 are designed to adapt to different

I am looking to implement responsive image sizing based on the webpage size. My images come in two different sizes: <img src="images/img1.jpg" data-big="images/img1.jpg" data-small="images/img1small.jpg" alt=""></img> The data-small image has ...

Removing scrollbar from table in React using Material UI

I successfully created a basic table using react and material UI by following the instructions found at: https://material-ui.com/components/tables/#table. The table is functioning properly, but I am finding the scrollbar to be a bit inconvenient. https:// ...

Various conditional statements based on the dropdown menu choice

I currently have a basic dropdown menu on my webpage that enables users to switch between viewing Actual or Planned dates/times in a table (I am utilizing the controller as syntax): <select ng-model="trip.viewType"> <option value="actual"> ...

What is the best way to modify a state in nextjs?

Recently, I've been working on a next.js project that includes a shopping cart feature. Essentially, when you click on an item, its image is added to a list and displayed with all the other selected items. To remove an item, users can simply click on ...

Creating variables in styled-components allows you to easily reuse values throughout

Can a variable be defined inside a styled-components component? The code snippet below, although not functioning properly, demonstrates my intention: const Example = styled.div` ${const length = calc(vw - props.someValue)} width: ${length}; &. ...

I'm encountering an issue where my information doesn't seem to be getting through to the Django

For some reason, the data I am trying to post to /api/recipe/recipes/ is not showing up in my HTML {% extends 'base.html' %} {% block content %} <!DOCTYPE html> <html> <head> <script src="h ...

If the option is 'Gel', use an if statement to console log

I'm trying to console.log the option from the data() function that is equal to 'Gel'. I attempted to use an if statement, but it doesn't seem to be working. Anyone have any ideas on how to make this work? data(){ return { ...

Tips for customizing the appearance of the day button in a React Material-UI date picker

In my React project, I am using material-ui date picker and I am looking for a way to customize the styling of the day buttons. Specifically, I want to change the text color of the available days. By default, as seen in the screenshot, the text color is bl ...

A Guide to Setting the HTML Lang Attribute on a Specific Page in Next.js

I have a website built with Next.js that consists of several pages. Most of the pages are in English, but there is one page that is in French and does not have an English version. How can I assign the lang attribute to the HTML tag for this specific page ...

Is there a way to update a data element within a $.get request by utilizing information from a JSON array?

Is there a way to dynamically change a data element in a $.get request using values from a JSON array? Let's take a look at an example code snippet that achieves this: $.get(url, { 'p': testerName, ...

I am looking to ensure that the ul li a() elements remain hidden until I hover over the h2 tag, at which point they will be displayed

Insert your code here : <table cellpadding="0" cellspacing="0" align="center" class="TblGreen"> <tr> <td> <h2><a href="#" class="AGreen">Sweater</a></h2> <p>The coding business</p> ...

When developing a node.js project using VMWare's shared folder, how can you manage the node_modules folder?

My current project needs to run on Linux, but I am using a Windows computer. This means I have to use a VM. Despite wanting to use WebStorm, I am avoiding JB Gateway due to its numerous bugs. My solution was to utilize the VMWare share folder function. Ho ...

The property 'filter' is not recognized on the 'Object' type. An attempt to filter the response was made

Trying to fetch data from a JSON file that matches the player's name in the URL, such as localhost:4200/players/Febiven, should only retrieve information about Febiven. The code is written in Angular 6. The current code snippet is as follows: player ...

Switch between input and the input is not displayed inline

I've been struggling to align the Toggle button with the input box for quite some time now. I really need them to be inline so that they form a grid properly as everything is dynamic. I have experimented with using a Div on its own instead of a label ...

AngularJS $http get isn't functioning properly, but surprisingly $.ajax works perfectly

Recently delving into the world of AngularJS, I am facing a hurdle with $http functionality. In my factory setup below: app.factory('employeeFactory', function ($http) { var factory = {}; // Retrieving data from controller var emplo ...

In order to determine if components linked from anchor elements are visible on the screen in Next.js, a thorough examination of the components

Currently, I am in the process of developing my own single-page website using Next.js and Typescript. The site consists of two sections: one (component 1) displaying my name and three anchor elements with a 'sticky' setting for easy navigation, a ...

Comparison Between Jquery and Emerging Javascript Frameworks and Libraries such as Angular, Ember, and React

As a ruby on rails developer, my recent foray into learning Angular and React has opened up new possibilities in the world of Javascript technologies. Despite reading comparison posts to gain insight into the reasons behind using different frameworks and l ...