Conceal specific elements within jQuery depending on the selected option

I am currently working on a filtering tool that utilizes a select element. The functionality I am aiming for is that when an option is selected from the drop-down menu, only the corresponding div below should be displayed while hiding the others.

To achieve this, I am using the select value as the class name of the targeted div. For instance, selecting "Shirts" would assign the class item-shirts to the div containing shirt-related content.

I have managed to successfully hide all other divs that do not match the selected item's class. However, I am struggling with restoring visibility to all divs when another selection is made. Any assistance on resolving this issue would be greatly appreciated!

Below is a snippet of my HTML code:

<select>
   <option value="item-shirts">Shirts</option>
   <option value="item-shoes">Shoes</option>
   <option value="item-pants">Pants</option>
</select>

<div class="item-section item-shirt></div>
<div class="item-section item-shoes></div>
<div class="item-section item-pants></div>

And here is the jQuery script I am using:

$('select').on("change", function() {
    var value = $('select').val();
   if($('.item-section').hasClass(value)) {
      $('.item-section.'+value).siblings().hide();
   } else {
      $('.item-section.'+value).siblings().show();
  }

Answer №1

It's like assigning an active class to a group of elements. The usual approach involves iterating through all elements, removing the active class from each one (even though it only applies to one), and then adding the active class to the specific element. In your scenario, you may need to hide all DIVs first and then reveal the specific DIV.

var $sections = $( '.item-section' );

$('select').on( 'change', function ( e ) {

  $sections.hide();
  $( '.' + this.value ).show();
  
} );
.item-section {
  margin: 2rem 0;
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select>
   <option value="item-shirts">Shirts</option>
   <option value="item-shoes">Shoes</option>
   <option value="item-pants">Pants</option>
</select>

<div class="item-section item-shirts">Shirt</div>
<div class="item-section item-shoes">Shoes</div>
<div class="item-section item-pants">Pants</div>

Note: There were some markup errors that I corrected for everything to function properly. For example, duplicate values in your <option> tags and missing quotes.

I've also made a couple of performance enhancements.

  • You can use this.value instead of $( 'select' ).val() within your event handler since the context is already the <select> element. This way, you avoid unnecessary DOM querying with jQuery.
  • I've optimized by caching the .item-section elements so that you don't have to query the DOM repeatedly on every select change.

Answer №2

Testing for hasClass() was unnecessary in this scenario. Simply retrieve the selected option value and display the corresponding <div> with that class. I included an extra empty option to show all <div>s when selected.

$('select').on("change", function() {
  var value = $('select').val();

  if (value) {
    $(".item-section").hide();
    $("." + value).show();
  } else {
    $(".item-section").show();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
   <option value=""></option>
   <option value="item-shirt">Shirts</option>
   <option value="item-shoes">Shoes</option>
   <option value="item-shoes">Pants</option>
</select>

<div class="item-section item-shirt">Shirts</div>
<div class="item-section item-shoes">Shoes</div>
<div class="item-section item-pants">Pants</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

unable to retrieve the response from a POST request sent to a node server

Currently in the process of learning how to utilize node and express, I have embarked on creating a sample website that incorporates both along with the Google translate API. The goal is to explore the numerous features offered by these technologies. Unfor ...

Having trouble with the dropdown feature on AngularJs?

Encountering an issue while trying to display the dropdown list. Upon inspecting in Chrome, it seems like the data is loading correctly but when clicked, the dropdown menu does not show up. The data is fetched from the BooksController and all options are ...

Executing JavaScript when a specific portion of a webpage loads in the presence of AJAX: A guide

As I tackle a project that involves loading elements via AJAX within a CMS-type software, I find myself restricted in accessing the AJAX code and its callbacks. One specific challenge I face is running my function only when a certain part of the page is l ...

What are the steps to creating a fading effect for an item that appears as it enters the field of view and disappears as it exits the field of view?

Implementing a fade-in effect for a button as the user scrolls down and the button comes into view, along with a fade-out effect as the user continues scrolling down and the button goes out of view. var fadeInButton = $('#fadeInButton'); ...

Display hyperlink depending on spinner value

I stumbled upon this JavaScript spinner that displays a countdown feature, which I find quite interesting. The spinner counts down from 15 seconds. I'm curious if it's feasible to customize it so that if you land on a specific category like geogr ...

What is the best way to trigger useEffect when the state being used within the effect is expected to change during the course of the effect's

Exploring the following code snippet: const [list, setList] = useState([]); const [curPage, setCurPage] = useState(0); const fetchItem = useCallback(async ()=>{ const data = await callAPI(); // data is an object setList(prev => [...prev, data]) ...

Accessing a variable from an external JavaScript file using jQuery

Can someone help me out with this issue I'm facing? I am having trouble getting a string returned to a variable in my embedded Javascript code. token.js: function token () { return "mysecretstring"; } HTML Code: <!DOCTYPE html> <h ...

Looking for a dynamic submenu that remains active even after refreshing the page? Check out the jQuery

I encountered an issue with a menu I created using jQuery. When clicking on a submenu, the site refreshes and then the menu does not remain in the active state. I want it to stay active showing its menu and submenu when clicked. I have also created a fid ...

Ways to display an HTML code by utilizing the onclick() function through PHP?

I have a button that looks like this: <input type="submit" name="submit5" class="btn" value="Add Date" onclick="create_date_field()" /> Every time the button is clicked, I want to append the following code inside the <tr> tags. It should be po ...

Discovering phrases and adjusting the hue

Is there a way to change the color of text output by the ECHO function using CSS and conditions? For instance: If I use the ECHO function to display text like this: echo ": The net value of the entire order" echo ": The gross value of the entire order" ...

Handling every promise in an array simultaneously

I am facing a problem with my array inside Promise.all. When I try to execute a function for the last iteration of forEach loop, I notice that my count_answers variable is only being set for the last object. This can be seen in the log output; the count_an ...

Is there a way to add a new button each time a different model is inserted by someone?

My goal is to add a new button each time a new data for a car make is added. However, currently the button keeps getting appended to the same button instead of creating a new one. How can I ensure that a new button is created for each data entry? $.ajax ...

Ways to retrieve information from a different website's URL?

Having a bit of an issue here. I'm currently browsing through some reports on webpage #1 () and I have a specific requirement to extract the object named "data" from webpage #2 (). However, the code I've used seems to fetch the entire webpage ins ...

How can I get my HTML DIVs to automatically move downward instead of upwards?

I'm currently developing a chat script that includes the feature to minimize specific chats, but I've encountered an issue with making the header of the div push down. Despite researching extensively, I haven't been able to find a solution t ...

Utilizing Next.js to dynamically update data within a div element upon

I have a table set up to display data and I want to transfer the row data into a div when the user clicks on a table row: Currently, I can successfully get the data onclick: const handleClick = (rowData) => { console.log(rowData); } However, I am ...

Linking two directives in AngularJS to the scope models of a parent controller

In my form controller, I have 2 object models: model1 - {name:"foo"} and model2 - {name:"model2"}. To implement this, I created 2 directives with isolated scopes. One directive binds only to elements and uses model1, while the other binds only to attribute ...

What methods are available to apply a class to an element in an array when hovering over it?

Is there a way to add a class to an element when hovering over it in an array of elements? ...

Guide to crafting a reply using nestjs exception filters with nestfastify

I'm facing a challenge with writing custom HTTP responses from NestJS exception filters. Currently, I am using the Nest Fastify framework instead of Express. I have created custom exception filters to handle UserNotFoundException in the following mann ...

After refreshing, the LocalStorage in Angular 2 seems to disappear

Something a little different here :) So, when attempting to log a user in, I am trying to store the access_token and expires in localStorage. It seems to be working "okay". However, if I refresh the page, the tokens disappear. Also, after clicking the log ...

Troubleshooting: Why isn't my ASP.NET Razor Pages WebMatrix AJAX post functioning properly?

Seeking assistance with posting data to a page using ajax, but encountering issues. Any suggestions? $.ajax({ url: '/REST/GetResponse.cshtml', type: "POST", dataType: "json", contentType: "application/json; charset=utf-8", d ...