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

Can you explain the functionality of this combination of jquery and form elements?

I have been working on jQuery code that looks like this: function submitFormData() { $('#myform').attr('action', "./filterData.action"); $('#myform').submit(); } Here is the form being referenced: <form name="myf ...

Tips for creating a dynamic menu item that stands out with a highlighted style

I would like to add a colored square to highlight the active menu item. .main-menu ul { padding: 0; margin: 0; text-align: center; } .main-menu li { list-style-type: none; display: inline-block; padding: 40px 0; } .main-menu a { font-fam ...

Tips on setting up a self-start event or alert in ASP.NET

I am trying to figure out how to trigger an alert for the user once a specific time has been reached. The challenge is that it cannot be initiated by a button click event or any other action. I want the alert to be displayed even if the user is on a diff ...

How can I display a popup window within an iframe on a separate full page?

I am facing an issue while creating an HTML table using AngularJS with a popup. The problem is that I want the popup window, which shows a graph, to open up on the entire page instead of in a specific div. My desired output should look like this: Currentl ...

I incorporated a CSS file from another HTML document. What do you think about that?

In my work with Ionic 3 and angular 4, each HTML file is accompanied by its own CSS file. There are times when I reference a class in one HTML file that is defined in another HTML file. I have observed that this CSS class gets injected into the main.js He ...

When the session times out, Ajax mistakenly displays the login page instead of an error message

I have a question that is somewhat similar to this one, but I will explain my understanding of the situation and the ideas I have come up with to fix it. Hopefully, someone can guide me in the right direction. The scenario: In my webapp, an authenticated ...

Keep things in line with async functions in Node JS

Hello, I am just starting out with NodeJs and I have a question. I am trying to push elements into an array called files based on the order of the urls provided, but it seems like I'm getting a random order instead. Below is the code I've been wo ...

Storing the ID passed from Next.js/Link into Next.js

I'm encountering some issues with the current flow setup. I have a component ArticleList that listens to articles, and upon clicking on it, redirects you to the individual article page. The redirection is done using next/Link, where the id is passed a ...

Exploring the gridview with JQuery to iterate through and verify if any checkboxes have been selected

I am currently working on a jQuery-based application. In this application, I have an ASP.net GridView that contains checkboxes in each row. My goal is to determine whether any of the checkboxes are checked or not. Below is the code snippet where I loop thr ...

Search Bar on the Website for Google Search

I am currently working on a basic website and I'm looking to incorporate Google Search functionality into it. I've managed to create a simple search box that redirects users to the Google Search Results page when they input their query. However, ...

Issue with resizing a Bootstrap pill containing truncated text

After struggling with this issue for some time, I attempted to use javascript to solve it but have been unsuccessful. The challenge involves a tag list in a table that displays a link when hovered over. Following advice from another member on SO, I managed ...

Submitting an HTML form results in no data being sent

I am currently facing an issue with a form on my website. The form code is as follows: <form action="" method="post" id="login_form"> <input type="text" name="log_login_form"/> <br/> <input type="password" name="log_password_for ...

In order to activate the button, make sure all 3 boxes are checked

Can someone provide some guidance on the script below? I'm utilizing it for a pop-up when a user attempts to add a product to the cart. Presently, the button will activate if at least one checkbox is selected (although it's not working on fiddle ...

placing a div inside another div

As I work on my website, I have created several panels with a repeating texture. To enhance the visual appeal of the site, I decided to add colored divs and adjust opacity for a tint effect instead of using separate images. The issue I'm facing is th ...

What is the purpose of encoding the Jquery Ajax URL twice?

In my JavaScript code, I am utilizing the jQuery ajax function. Here is an example of how it appears: $.ajax({ url: "somepage/" + keyword + "/" + xyz + "/" + abc + "/getbla", (...) If the 'keyword' (value from a textfield) includes a ' ...

Placing an image on the chosen option of a <mat-select> using Angular Material

I have incorporated Angular Material into my Angular 2 project, and I am trying to insert a static image (HTML element) in the selected value of mat-select. Unfortunately, I have been unable to find a solution for this issue. Is there anyone who can ...

Bootstrap Modal closing problem

While working on a bootstrap modal, I encountered an issue where the modal contains two buttons - one for printing the content and another for closing the modal. Here is the code snippet for the modal in my aspx page: <div class="modal fade" id="myMod ...

My bootstrap collapse navbar isn't functioning properly. Despite pressing the icon on a smaller screen, the menu fails to open. Can anyone provide a solution to this issue?

The hamburger menu is not working properly. I am facing an issue where the navigation does not appear when I press on the hamburger icon on a small screen. Can someone please guide me on how to resolve this problem? :/ <nav class="navbar bg-d ...

Fetching JSON data from a Node.js server and displaying it in an Angular 6 application

Here is the code snippet from my app.js: app.get('/post', (req,res) =>{ let data = [{ userId: 10, id: 98, title: 'laboriosam dolor voluptates', body: 'doloremque ex facilis sit sint culpa{ userId: 10' ...

What is the solution for the error "does not exist on type 'HTMLTableDataCellElement'" in Angular?

When working on my Angular project, I implemented a PrimeNG p-table component. <p-table [value]="users" class="user-roles-table" [rows]="5" [showCurrentPageReport]="true" [ ...