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

Requesting PayPal for an HTTPS transaction

When attempting to call the Express Checkout Paypal API using $http.get(AngularJS), I encountered error 81002(Method Specified is not Supported). However, when I tried calling the API using the search bar in Google Chrome, I was able to retrieve the token ...

Creating a standard login.js file for seamless integration with nightwatch.js testing

When creating tests for my web application, I need to first simulate a login before proceeding with the rest of the tests to access inner pages. Currently, I am in the process of refactoring the code so that I can create an 'include' for common f ...

Sending dynamic information to bootstrap's modal using props in VueJS

I'm currently working on a personal project and encountering an issue with the bootstrap modal. My project involves a list of projects, each one contained within a card element. The problem arises when I attempt to display details for each project by ...

Is there a way for me to display the image name at the bottom before uploading it, and have a new div created every time I upload an image?

Is there a way to display the image name at the bottom and have it create a new div every time an image is uploaded? I would appreciate any help with this... <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstra ...

Incorporating the outcome of an asynchronous function into my 'return' statement while iterating through an array

Issue I am Facing I encountered a problem while trying to execute a database function while simultaneously mapping an array. To illustrate this problem in a more concise manner, I have developed a sample code snippet. In my implementation, I am utilizing ...

The dropdown menu is malfunctioning when accessed within the mobile view of a jQuery

Take a look at this code snippet on Fiddle: https://jsfiddle.net/rizwanali98601/ngofhc24/12/. The table below contains a dropdown inside a jQuery Datatable. When the button is clicked, an option is supposed to be added to the dropdown. However, in mobile ...

Transferring information between Vue.js components via data emissions

Greetings from my VueJS Table component! <b-table class="table table-striped" id="my-table" :items="items" :per-page="perPage" :current-page="currentPage" :fields="fields" @row-clicked="test" lg >< ...

Tips for accessing the HTML content enclosed within a specific HTML tag using Python with Selenium

I am trying to extract the source code of an HTML document that is embedded within an <iframe> tag generated by JavaScript. The HTML contents within this <iframe> tag appears as #document, which expands to reveal a full HTML document starting w ...

What could be causing the unexpected behavior in my NgMessages form validation?

I have developed a code that incorporates Angular JS form validation methods. There are two separate forms within the codebase, The initial form utilizes basic form validation while the second form employs ng-messages, However, an issue has arisen wher ...

Transition one background image into another using background positioning

Snippet of code: https://jsfiddle.net/foy4m43j/ HTML: <div id="background"></div> CSS: #background { background-image: url("http://i.imgur.com/hH9IWA0.png"); background-position: 0 0; background-repeat: repea ...

Enhancing the alignment of div elements

Our objective is to have two divs aligned next to each other. Here is the HTML code: <div class="test1>Text 1</div> <div class="test2>Text 2</div> And here is the CSS code: .test1 { float: left; } .test2 { float: left; } ...

Steps to automatically navigate to a specific Div upon page initialization

Can someone help me understand why my code is scrolling to a div and then returning back to the top of the page? $("#Qtags").click(function(){ $('html, body').animate({'scrollTop' : $($(this).attr('href')).offset().top}, ...

The proper way to define an event delegator's syntax

Typically, when you want to handle a button click event, you would do so like this: $(document).ready(function() { $("button").click(function() { doSomething(); }); }); However, in the scenario of an event delegator, you may need to respon ...

When a website is deployed to an application, the process includes MVC bundling and managing relative CSS image paths

When trying to convert relative image paths to absolute paths, there are numerous queries on stackoverflow addressing this issue. For example, take a look at this thread: MVC4 StyleBundle not resolving images This question recommends using new CssRewrite ...

How can one leverage Node JS to effectively manage events?

Is it considered a best practice to utilize events for communication between functions within ExpressJS? If so, what is the proper way to send arguments along with my emit event? ...

Heroku-hosted application experiencing issues with loading website content

I have been working on a nodejs application that serves a web page using express and also functions as a discord bot. The app runs smoothly on localhost with both the web page and discord functionalities working correctly. However, when I deploy it to Hero ...

Issue: .catch(error) function in Node / Express not returning as expectedDescription: After

I'm currently developing a REST API and focusing on effectively managing all error scenarios. Upon successful completion of the API call, I make sure to return the success object to the calling function and then send the response to the client. Howev ...

MVC.NET: Offering User-Friendly Loading of Initial x Items with an Option to Load More

What would be the optimal approach to efficiently load only the initial 25 elements from an IEnumerable within an ASP.NET MVC Index view? Upon employing scaffolding, a controller and views have been constructed. Within the index page, there is a creation ...

Heroku is showing an Error R10 (Boot timeout) message, indicating that the web process was unable to bind to the designated $PORT within one minute of launching

Encountering an error while trying to deploy my first node project on Heroku. Here is the error message: 2020-09-29T04:24:09.365962+00:00 app[web.1]: production 2020-09-29T04:24:09.415266+00:00 app[web.1]: server is listening at port 40890 2020-09-29T04:24 ...

Guide on utilizing Nextjs middleware for directing users to sub-domain according to their IP address

I've been struggling to effectively implement NextJs's middleware for redirecting users from a specific country to another web domain. I've encountered some issues with my setup: Main domain: https://www.example.com sub-domain: src/middle ...