Looking to display or conceal several divs according to the option selected from a dropdown menu?

I've been searching for a solution to my simple dropdown issue, but haven't had any luck in the forums. This is the code for the dropdown:

<select id ="category_faq">
     <option value="1">item1</option>
     <option value="2">item2</option>
     <option value="3">item3</option>
</select>

The corresponding divs are:

<div class="views-row-1"></div>
<div class="views-row-2"></div>
<div class="views-row-3"></div>

My goal is for selecting each item in the dropdown to show only the relevant div and hide the others.

Here's the jQuery script I'm using:

jQuery(document).ready(function($) {
      $('#category_faq').on('change',function() {
         if(this.value=='1')
            {
                $('.views-row-1').show();
            }
        else if (this.value=='2') 
             {
                $(".views-row-1").hide();
                $(".views-row-2").show();
                $(".views-row-3").hide();
            }
        else
             {
                $(".views-row-1").hide();
                $(".views-row-2").hide();
                $(".views-row-3").show();
             }

    }); 

}); 

Unfortunately, this script doesn't seem to be working. Can anyone help me identify where I may have gone wrong?

Answer №1

A simplified version would be:

$('#category_faq').on('change', function () {
    $('div').hide();
    $('div.views-row-' + $(this).val()).show()
});

Example on jsFiddle

Answer №2

To simplify the process of showing/hiding divs, it's recommended to assign a common selector to all the divs you wish to manipulate:

<div class="item item-1"></div> 
<div class="item item-2"></div>
<div class="item item-3"></div>

Afterwards, set each div to be hidden by default and only display when triggered by the selected value:

$('#category_selector').on('change',function() {
   var selectedValue = $(this).val();
   $(".item").not('.item-'+selectedValue).hide(); // Hide all items
   $(".item-"+selectedValue).show(); // Display selected item
}); 

Answer №3

http://jsfiddle.net/3bqmv19j/

$('section').hide();
$('.gallery-item-' + $('#selected_category').val()).show();
$('#selected_category').on('change', function () {
    $('section').hide();         
    $('.gallery-item-' + $(this).val()).show();
});

Make sure to set the initial display based on the default value of the select menu. Then, simply hide all sections and only show the one corresponding to the selected category when it changes.

Answer №4

Give this a shot:

  $('#category_faq').on('change',function() {
      $('div[class!=views-row-]').hide();
      $('div.views-row-' + this.value).show();
  }); 

Check out the live demo

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

What could be causing the DATE_SUB function to fail in executing a MySQL query through Node.js?

I am encountering an issue with a datetime field in a MySQL database table on Planetscale. My goal is to subtract some time from the datetime value using the DATE_SUB function. While this operation works smoothly in the database console on Planetscale&apos ...

There are two separate CSS files linked to the same page, but the browser is only rendering the styles from

I am in the process of developing a new web page where I want to implement my own CSS and incorporate some components from this source: . I'm facing an issue with one of the components, as the browser seems to be applying only the styles from my custo ...

Unable to retrieve the value of a clicked button using jQuery

i am attempting to extract an array from checked buttons when a button is clicked. Although I can successfully retrieve the array, I am struggling to obtain the value of the clicked button. the code snippet below illustrates my attempt: $('.multiple& ...

Steps to create an if statement using jQuery

.data( "autocomplete" )._renderItem = function( ul, item ) { return $( "<li></li>" ) .data( "item.autocomplete", item ) if ( ( item.parent_term_id == "16" ) ) { .append( "<a>" + (item.child_term ? item.child ...

Tips for ensuring an HTML element remains within defined boundaries

Currently working on a visualization tool for search algorithms using React, I've encountered a minor issue when moving the start or end nodes. Upon clicking and dragging the mouse across the grid, the nodes adjust accordingly until reaching the grid& ...

How can I effectively retrieve the JWT in a node environment?

I've successfully set up JWT authentication using Node.js. After the user signs in, Node.js generates a JWT and sends it back to be stored in the localStorage. However, I've encountered an issue when trying to access this token within the express ...

Endlessly tapping through each tab with no direction

I am attempting to click on all unopened tabs (elements) randomly across this page. While the code below usually does the trick, it sometimes doesn't click on all elements. I suspect that there might be an issue with how it loads indexes or some othe ...

Creating a Breeze js entity using a JSON string and importing it into the breeze cache: A step-by-step guide

Currently, I am developing a mobile single page website that utilizes technologies like breeze js, angular js, web API, and entity framework. To enhance the performance of the site, I have decided to include the breeze metadata in a bundled JavaScript fil ...

Embed array inside angular directive

In my angular application, I have a code snippet that generates a navigation tree within a <div>. The size of this tree depends on the contents of mymodule.tree.folders. To enhance this functionality, I want to create a directive named class="scrolla ...

Issues with Thunderbird not displaying copied HTML emails

Hello there amazing people at Stackoverflow. I need some assistance with HTML formatting. I am currently working on a bootstrap modal that is being dynamically modified through jQuery using the append() function. Check out the code snippet below: <div ...

Twofold Arrow Styling in CSS

Can someone help me achieve this design: https://i.stack.imgur.com/eBQ1a.png I am attempting to create a double arrow using just one class. I have tried various methods, but nothing seems to be working for me. If anyone has any suggestions or can point ...

Reducing the amount of text displayed on ion-text to a minimum

HTML: <ion-list *ngFor="let message of messages"> <ion-item lines="none" type="button" button="true"> <ion-grid> <ion-row> <ion-col class="message"> <ion-text> ...

Combine React 17 with webpack 5 and babel-plugin-react-css-modules, enabling the use of CSS modules with stylename functionality

I am in the process of setting up a new React application using the latest technologies available, including React 17, Webpack 5, and other essential modules. My goal is to implement CSS modules utilizing the styleName concept with the help of babel-plugi ...

What is the process for saving an SVG element from an HTML page as a downloadable text file?

I've been practicing creating SVG elements from scratch on an HTML page using Javascript. The texts within the SVG element are styled with typefaces fetched from the server through a "@font-face" declaration in the CSS file. It's been quite succe ...

TSLint is encountering the error code TS2459: The module "@azure/core-tracing" claims to have a local declaration of "Span" but does not export it, along with additional errors

I'm completely lost on how to tackle this error. The message I'm getting doesn't provide much insight, other than indicating an issue with the installation of '@azure/ai-text-analytics'. I've gone through the process of uninst ...

Create a function called "insertEvent" that will insert a new event on a specified date

Below is the data structure for storing affairs according to years, months, and days: let affairs = { 2018: { 11: { 29: ['task111', 'task112', 'task113'], 30: ['task121', 'ta ...

Guide to modifying Button on fetch response in React Native

After receiving a response from the server, I need to adjust the button based on the friends_status field in the following response: { "responseHeader": { "type": "314", "status": "200", "message": "Successfully found the profile" }, "ne ...

Challenge in Decision Making

I am curious why this type of selection is not functioning properly for html select options, while it works seamlessly for other input types like Radios or checkboxes. Any thoughts? $('#resetlist').click(function() { $('input:select[nam ...

QuickCopy - Capture only what's in view

Hi there, I have a question: I'm trying to figure out how to make a button copy only the visible text within the element with id="description". Can someone help me troubleshoot? HTML: <p id="description"> Test <span style="display:none"> ...

Angular Material Popup - Interactive Map from AGM

I am in the process of developing a material dialog to collect user location information using AGM (angular google maps). I have successfully implemented a map on my main page, but when the dialog is opened, it only shows a blank space instead of the map. ...