jQuery: Revealing or concealing several divs upon selection alteration

When I populate a form, I want to display or hide multiple divs based on the OPTION selected in a DROPDOWN.

Currently, my code works but the issue is that one div can be hidden or shown by multiple OPTIONS. As a result, these divs keep toggling between hidden and visible states.

Below is the HTML snippet:

<select id="vFormat" name="vFormat" onchange="getval(this);">
    <option value="0">Choose</option>
    <option value="1" class="format1">Option 1</option>
    <option value="2" class="format2">Option 2</option>
    <option value="3" class="format3">Option 3</option>
    <option value="4" class="format4">Option 4</option>
    <option value="5" class="format5">Option 5</option>
</select>

<div class="showdivformat1 showdivformat2 hiddenelement">
   Text inside hidden Div
</div>

<div class="hidedivformat2 showdivformat5 visibleelement">
   Text inside visible Div
</div>

This is the JQuery functionality:

function getval(sel) {

    var divval = $('.selectInput option:selected').attr('class').split(' ');

    for(var i=0; i<divval.length; i++){
        $(".hiddenelement").hide("50");
        $(".showdiv" + divval[i]).show("50");
    }

    for(var i=0; i<divval.length; i++){
        $(".visibleelement").show("50");
        $(".hidediv" + divval[i]).hide("50");
    }       
}

The challenge lies in always hiding .hiddenelement and showing .visibleelement whenever the option changes.

I am exploring solutions to detect if a div is already hidden or visible and maintain its state after the option change.

Answer №1

Take a look at this simplified and organized solution:

HTML:

<select id="vType" name="vType">
    <option value="0">Select</option>
    <option value="1">Type 1</option>
    <option value="2">Type 2</option>
    <option value="3">Type 3</option>
    <option value="4">Type 4</option>
    <option value="5">Type 5</option>
</select>

<div class="hide-default show-3-and-4" >
   Displayed with options 3 and 4
</div>

<div class="show-all hide-4" >
   Always displayed, except with option 4
</div>

JavaScript:

$('#vType').change(function() {
    $('.hide-default').hide();
    $('.show-all').show();

    $('.show-' + $(this).val() + '-and-hide').show();
    $('.hide-' + $(this).val()).hide();
}).change();

You can view the code on JSFiddle: https://jsfiddle.net/abcdefg123/

To add more elements with default visibility settings, use classes like hide-default and show-all. Similarly, for specific display based on selected option, utilize classes such as show-X and hide-Y.

Answer №2

The issue you are facing may require some clarification, but one potential resolution could involve toggling classes to hide and show the div element.

Answer №3

Organize arrays containing jQuery Objects for each group of elements. When the user selects an option, use a conditional statement to loop through the corresponding array of jQuery objects and hide or show them accordingly.

// Psuedo Code...

var elemGroupOne = [], elemGroupTwo = [];

// Add divs to the arrays 
elemGroupOne.push(/* jQuery Object... */);

$("#vFormat").on("change", function(event) {
   var selectedValue = $(this).val();

   switch (selectedValue) {
       case "Option 1":
            // Hide group two..
            for ( i = 0; i < elemGroupTwo.length; i++ ) {
                var el = elemGroupTwo[i];
                $(el).hide();  
            }

            // Show group one..
            for ( i = 0; i < elemGroupOne.length; i++ ) {
                var el = elemGroupOne[i];
                $(el).show();  
            }
           break;

       case "Option 2":
            // Hide group one..
            for ( i = 0; i < elemGroupOne.length; i++ ) {
                var el = elemGroupOne[i];
                $(el).hide();  
            }

            // Show group two..
            for ( i = 0; i < elemGroupTwo.length; i++ ) {
                var el = elemGroupTwo[i];
                $(el).show();  
            }
           break;
   } 
});

This code can be optimized further, but I hope it gives you some insights on how to approach your question effectively.

Answer №4

Here is a possible solution:

<div class="showdivformat1 showdivformat2 hiddenelement" id="div1">
  Text of hidden Div
</div>

<div class="hidedivformat2 showdivformat5 visibleelement" id="div2">
  Text of visible Div
</div>


function getval() {

    var divs = document.getElementsByTagName("div");

for(var i=0; i<divs.length; i++){
    $("#div"+i).hide("50");
    $("#div"+i+1).show("50");//any other way to identify ur identity of div and u are done
}

for(var i=0; i<divval.length; i++){
    $(".visibleelement").show("50");
    $(".hidediv" + divval[i]).hide("50");
}       
}

If this helps, please let me know.

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

Proper approach for mapping JSON data to a table using the Fetch API in a React.js application

Struggling to map some elements of JSON to a Table in Customers.jsx, but can't seem to figure out the correct way. How do I properly insert my Fetch Method into Customers.jsx? Specifically managing the renderBody part and the bodyData={/The JsonData/} ...

Tips for verifying the rendered view post data retrieval from an API in Vue JS

Having trouble retrieving data from the API using Vue JS and printing the page? After fetching the data, some elements may not render completely when trying to print, resulting in blank data being displayed. While using a setTimeout function may work for s ...

Troubles with CSS drop down alignment in Internet Explorer 7

I've been racking my brain all morning trying to solve this issue. My current project involves creating a website for a client, and I'm having trouble getting the dropdown menu to position correctly in IE7. It's working fine in all other br ...

How can I create a CSS div with a 20px margin-top distance from the div directly above

Here is the code that I am working with: https://jsfiddle.net/kc94aq33/ I am looking to set the top margin of the .wrapper to be 20px from the bottom of the .header. Does anyone know how I can achieve this? ...

Extracting data from the response object and injecting it into the request

Once the file has been successfully uploaded, the 'uploadSuccess' callback event is triggered, providing information about the newly created media. The 'hashed_id' value within this object is crucial for my PUT request. I attempted to ...

Having trouble establishing a connection between socket.io client and server

I am currently attempting to establish a connection between a client and server using express and node.js. Unfortunately, I am encountering difficulties in connecting to the server. The tutorial I followed (available at https://socket.io/get-started/chat) ...

Error: The function $scope.apply is invalid and cannot be executed

I am attempting to display the contacts list after retrieving it using rdflib.js. The data is being loaded and stored in the list within the scope. However, I am running into an issue where the $scope is not updating, and it appears that I may be calling ...

Tips for automatically refreshing a page after submitting a form

I have a template with two components - a filter and a request to the API. I am wondering if it's possible to update the values of the request component after submitting the filter. On the main page, the request component has default values. When a u ...

Guide on making nested ajax calls and passing object data to controller in ASP.Net MVC 5

I currently have two controllers set up: Settings Controller Action - GetAvailableLocationsFor HomeController Action - Index My goal is to achieve the following steps: Initiate an ajax call to GetAvailableLocationsFor and retrieve object data from t ...

Having a CSS position fixed within a div container with the same width as its parent container

At the moment, I have three sections: left, center, and right. I want to add a fixed position div (notification) inside the center section so that it remains in place when scrolling. Additionally, I want this notification to resize according to changes in ...

When the ID and anchor link within a URL fail to scroll to the specified anchor location

I'm trying to add an id to a URL and scroll to an anchor link <a name="tags" id='tags'></a> <a href="edit.php?id=382#tags">GO</a> I have also attempted the following: <a href="edit.php?id=382&#tags">GO& ...

Rendering HTML with Apache Tiles using an empty <a></a> tag

Having encountered a peculiar issue with HTML lately. In my backend, the problematic section looks like this. <div class="content"> <a href="detail.html"></a> <img src="assets/i ...

creating images using express.js

Exploring the world of node.js and express.js is an exciting journey for me as a newcomer. I've been working on upgrading my front-end project with these technologies, and everything seems to be falling into place perfectly except for one roadblock - ...

Converting objects to arrays in reactJS

Here is the object structure I currently have: { DepositAmt_0: 133 DepositAmt_1: 455 DepositAmt_2: 123 DepositNotes_0: "some notes " DepositNotes_1: "some comment" DepositNotes_2: "some comme ...

Choose either immediate offspring or immediate offspring of immediate offspring

I am struggling to create a CSS Selector that follows DRY principles. The selector needs to target elements within a group but not those within a subgroup of the main group. Elements should only be direct children of the main group or wrapped in an addit ...

Sophisticated filter - Conceal Ancestry

Check out this snippet of my HTML: <td> <a class="button" href="#"> <input id="download">...</input> </a> <a class="button" href="#"> <input id="downloadcsv">...</input> </a> </td> I am ...

Omit punctuation from the key name in the JSON reply

Hey there, I'm a bit confused about why periods are being used in JSON key names. Basically, what I'm trying to accomplish is passing a JSON response through EJS variables into a page template and extracting the data into separate fields. Here& ...

retrieve information from the local JSON file

Hi there, I am looking to retrieve data from my JSON file and then display it in HTML. Before that, I want to simply log it in the console. How can I accomplish this task? The JSON file will be updated based on user input. varer.json [{"id":&qu ...

Interactive Dropdown Menus for 3 Separate Database Tables

Having trouble creating a dependent drop-down list and would appreciate some help. The error "Undefined variable: input" keeps showing up in my code. https://i.sstatic.net/mBurS.pngFor the initial drop-down, I have 3 fixed options. <option value="busin ...

The click() method within the click() function is malfunctioning

My issue arises when I click the delaccbut button. The click function triggers and displays a message, but then when I try to click either the confdel or redel button within the same function, nothing happens. Why is this occurring? HTML: <span id=&ap ...