How can you switch the display between two different class names using JavaScript?

I currently have a total of four filter buttons on my website, and I only want two of them to be visible at any given time. To achieve this, I labeled the first set of buttons as .switch1 and the second set as .switch2. Now, I've added a 'switch filter' button that, when clicked by the user, will toggle the display properties of these buttons; changing .switch1 from display:block to none, and .switch2 from display:none to block.

<div class="switch2">
   <label>Year</label>
   <select class="px-3 py-1 form-select bg-btn" aria-label="Default select example" style="font-size: 14px;">
      <option selected>2022</option>
      <option value="1">2021</option>
      <option value="2">2020</option>
      <option value="2">2019</option>
      <option value="2">2018</option>
      <option value="2">2017</option>
      <option value="2">2016</option>
   </select>
</div>
<div class="switch1">
   <label>From:</label>
   <input class="px-3 py-1 fr-to bg-btn" type="date" name="" id="" style="font-size: 14px;">
</div>
</div>
<div class="month-select col-2">
   <div class="switch2">
      <label>Month</label>
      <select class="px-3 py-1 form-select bg-btn" aria-label="Default select example" style="font-size: 14px;">
         <option selected>January</option>
         <option value="1">February</option>
         <option value="2">March</option>
         <option value="2">April</option>
         <option value="2">May</option>
         <option value="2">June</option>
         <option value="2">July</option>
         <option value="2">August</option>
         <option value="2">September</option>
         <option value="2">October</option>
         <option value="2">November</option>
         <option value="2">December</option>
      </select>
   </div>
   <div class="switch1">
      <label>To:</label>
      <input class="px-3 py-1 fr-to bg-btn" type="date" name="" id="" style="font-size: 14px;">
   </div>
</div>
<div class="ms-5 d-flex flex-column justify-content-end">
   <div class=""><button class="btn-dark px-3 py-1 filterbtn">Filter</button></div>
</div>

You can view how the first and second sets of buttons appear on my site in the following screenshots: first buttons second buttons

Answer №1

You could apply a hidden class to the initial set and then switch that class back and forth

let toggleButton = document.querySelector('button')
let section1 = document.querySelectorAll('.section1')
let section2 = document.querySelectorAll('.section2')

function toggleSections() {
  let elements = [...section1, ...section2]
  for (i = 0; i < elements.length; ++i) {
    elements[i].classList.toggle('hidden')
  }
}

toggleButton.onclick = toggleSections
.hidden {
  display: none;
}
<div class="section2 hidden">
  <label>Year</label>
  <select class="px-3 py-1 form-select bg-btn" aria-label="Default select example" style="font-size: 14px;">
    <option selected>2022</option>
    <option value="1">2021</option>
    <option value="2">2020</option>
    <option value="2">2019</option>
    <option value="2">2018</option>
    <option value="2">2017</option>
    <option value="2">2016</option>
  </select>
</div>

<div class="section1">
  <label>From:</label>
  <input class="px-3 py-1 fr-to bg-btn" type="date" name="" id="" style="font-size: 14px;">
</div>

<div class="month-select col-2">
  <div class="section2 hidden">
    <label>Month</label>
    <select class="px-3 py-1 form-select bg-btn" aria-label="Default select example" style="font-size: 14px;">
      <option selected>January</option>
      <option value="1">February</option>
      <option value="2">March</option>
      <option value="2">April</option>
      <option value="2">May</option>
      <option value="2">June</option>
      <option value="2">July</option>
      <option value="2">August</option>
      <option value="2">September</option>
      <option value="2">October</option>
      <option value="2">November</option>
      <option value="2">December</option>
    </select>
  </div>

  <div class="section1">
    <label>To:</label>
    <input class="px-3 py-1 fr-to bg-btn" type="date" name="" id="" style="font-size: 14px;">
  </div>

  <div class="ms-5 d-flex flex-column justify-content-end">
    <div class=""><button class="btn-dark px-3 py-1 filterbtn">Filter</button></div>
  </div>
</div>

Answer №2

let filterBtn = document.querySelector('.filterbtn');
let switch1 = document.querySelectorAll('.switch1');
let switch2 = document.querySelectorAll('.switch2');

filterBtn.addEventListener('click',function(){
    switch1.forEach(element => {
        element.classList.toggle('switch');
    });
    switch2.forEach(element => {
        element.classList.toggle('switch');
    });
});
.switch{
            display: none;
        }
<div class="switch2 switch">
   <label>Year</label>
   <select class="px-3 py-1 form-select bg-btn" aria-label="Default select example" style="font-size: 14px;">
      <option selected>2022</option>
      <option value="1">2021</option>
      <option value="2">2020</option>
      <option value="2">2019</option>
      <option value="2">2018</option>
      <option value="2">2017</option>
      <option value="2">2016</option>
   </select>
</div>
<div class="switch1">
   <label>From:</label>
   <input class="px-3 py-1 fr-to bg-btn" type="date" name="" id="" style="font-size: 14px;">
</div>
</div>
<div class="month-select col-2">
   <div class="switch2 switch">
      <label>Month</label>
      <select class="px-3 py-1 form-select bg-btn" aria-label="Default select example" style="font-size: 14px;">
         <option selected>January</option>
         <option value="1">February</option>
         <option value="2">March</option>
         <option value="2">April</option>
         <option value="2">May</option>
         <option value="2">June</option>
         <option value="2">July</option>
         <option value="2">August</option>
         <option value="2">September</option>
         <option value="2">October</option>
         <option value="2">November</option>
         <option value="2">December</option>
      </select>
   </div>
   <div class="switch1">
      <label>To:</label>
      <input class="px-3 py-1 fr-to bg-btn" type="date" name="" id="" style="font-size: 14px;">
   </div>
</div>
<div class="ms-5 d-flex flex-column justify-content-end">
   <div class=""><button class="btn-dark px-3 py-1 filterbtn">Filter</button></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

I am attempting to create a footer with a set size, but encountering an issue

I'm in the process of developing a responsive website using Vue.js. One aspect I am working on is the footer container, which looks fine on the full screen but shrinks when the screen resolution is reduced below 1100 pixels. As shown in the images li ...

Guide to adding an image with feathers.js and multer:

I am currently working on integrating feathers.js with React for my project and I am facing an issue with uploading images. I have tried using multer and busboy for handling the upload, but I am unable to successfully upload the image or access it through ...

Finding the index of a selected option in node.js can be achieved using express

I am trying to retrieve the index of the selected object using Express and log it in app.js example.html <form id="tableForm" action="getJson"> <select class="example" name="example"> <option name="table1" value="1"& ...

I keep encountering an error stating that parameter 1 for 'FormData' is not of type 'HTMLFormElement'. I am struggling to resolve this issue on my own. Can someone please assist me with fixing this problem?

Here is the snippet of code that I am struggling with: const authForm = useRef(); const handleSubmit = (e) => { e.preventDefault(); //formData let form = new FormData(authForm.current); console.log(form) } This code snippet shows how I added a ...

What is the proper method for utilizing colspan within the footerData of a jqGrid?

Are you looking to customize the footer of your jqgrid as shown in the example below? I am trying to set up a custom footer for my jqgrid similar to the one displayed above. I have already enabled the footerrow:true option and used $self.jqGrid("footerDat ...

The function was expecting an array for ordering, but instead received an object

I need help filtering my results based on their position. Whenever I try to use the orderBy function, it breaks the page because the result is not an array. How can I fix this issue? I'm currently stuck at this point. This is how I attempt to filter ...

Artwork expanding incorrectly on HTML canvas

I'm encountering an issue while attempting to draw on an HTML canvas. I've specified 50 circles and multiple lines within a canvas of size 1000x1000 px, but not all circles are appearing as expected. My assumption is that the elements are being ...

Why isn't pagination typically positioned inside of a tbody element rather than before or after it?

I've created a user table that is based on the number parameter. I added a filter that listens to input and performs an AJAX call each time with the filter applied to the name field. However, the pagination is initially displayed ABOVE the entire ta ...

Which symbol is preferable to use in JS imports for Vue.js/Nuxt.js - the @ symbol or the ~ symbol?

I am seeking guidance on a matter that I have not been able to find a clear answer to. Webapck typically uses the ~ symbol as an alias for the root directory. However, I have noticed that some developers use the @ symbol when importing modules using ES6 s ...

I am experiencing difficulty in detecting variable changes within my $scope function

I'm encountering an issue where a variable isn't being updated in a $scope function when there's a state change event. Despite seeing the variable update in the event listener, it doesn't reflect in the function. The code snippet in qu ...

Using JQuery and PHP to make an Ajax request and handle JSON response

I'm attempting to complete a straightforward exercise: The task involves entering two numbers in separate inputs, clicking a button, and seeing the result appear in a third input. sum.html: <html> <head> <title>Sum</tit ...

The Jquery AjaxStop event fails to trigger, but AjaxStart works perfectly

While I was working with APIs, I encountered a roadblock. I have a Jquery function that retrieves data from an API. To prevent a "reposition" effect, I need the function to wait until all calls are made before triggering another function to place all the ...

The functionality of the anchor tag is not supported by the Safari browser on iPhone devices

Having some trouble with a named anchor tag in the iPhone Safari browser. It's functioning properly in desktop browsers, including Safari, but not working on mobile Safari. Odd! For instance, my URL appears as: http://www.example.com/my-example-arti ...

What is the process for incorporating a unique Mongo expression into a JSON object?

I'm currently trying to figure out how to add a specific Mongo command to my JSON object. Normally, adding regular strings or objects is straightforward, but I'm struggling with this particular command: $set : { "author" : req.body.name } Simpl ...

Struggling to retrieve data from a MongoDB database in JSON format via an API call? If you're working with JavaScript, Node.js, Express, and MongoDB, we can help you

Below is how I establish the connection to the database: > // Connecting MongoDB using MongoClient > > const MongoClient = require('mongodb').MongoClient > > const url = 'url is used' > > const dbName = 'vir ...

Tips for separating these two words onto two separate lines

I created this box using Angular Material, but I am having trouble breaking the words "1349" and "New Feedback" into two lines. Here's an image included in my design. Any tips on accomplishing this in Angular Material? Thank you! <style> . ...

Implement Next.js deployment on NGINX server with a 403 forbidden error

I am currently utilizing Next.js for the frontend and Django for the backend. During development, everything is functioning properly. However, when transitioning to production, I am encountering a 403 Forbidden Error related to /_next/static/chunks. It app ...

The duplication of the Javascript code is creating a conflict within the slider functionality

Attempting to create both an image slider and text slider on the same page using the same JavaScript is proving to be a challenge. Despite researching and trying to implement a no-conflict solution, the sliders still do not function properly together. Wh ...

In React and Editor.js, the forEach method in the If/Else statement is successfully adding paragraphs but not headlines. Interestingly, this issue seems to be isolated

Looking for assistance with rebuilding my dashboard to React in order to use Editor.js for blog content instead of a textarea. Currently using Editor JS as the editor. On my local machine, everything is working perfectly. I write an article, click Create ...

Enhancing Next.js Images with Custom CSS Styles

I am working with a Next.js component: import styles from '../styles/Navbar.module.css' import Image from 'next/image' export const Navbar = () => { <div> <Image className={styles["navbar-home-icon"]} ...