How can I display different divs based on a selected option?

I'm encountering difficulties while attempting to develop the code for this specific task. My goal is to display or hide divs based on the selection made in a select option, with a total of 4 options available.

There are 2 select elements

<select>
    <option value="value1">Value 1</option>
    <option value="value2">Value 2</option>
</select>

<select>
    <option value="value3">Value 3</option>
    <option value="value4">Value 4</option>
</select>

The possible combinations are:

value1-value3 value1-value4

value2-value3 value2-value4

The second select element remains empty until an option is picked from the first select element. Once selected, the second select element becomes active and displays the corresponding div for that particular value.

The divs would be:

<div id="value-1-3">value1-value3</div>
<div id="value-1-4">value1-value4</div>

<div id="value-2-3">value2-value3</div>
<div id="value-2-4">value2-value4</div>

Would appreciate any assistance you could provide in accomplishing this task.

Answer №1

If you want to add some unique identifiers to your dropdowns, you can assign IDs like sel1 and sel2. Make sure to simplify the value in the option tags to just numbers to avoid extra processing:

$("#sel1").change(function() {
    $("#sel2").prop("disabled", false); //Enable the second dropdown
    $("#sel2").change(); //Trigger a change event on the second dropdown
});

$("#sel2").change(function() {
    //Get values of both dropdowns
    var sel1Value = $("#sel1").val();
    var sel2Value = this.value;

    //Combine selectors and display the result
    $("div").hide(); //Hide previously shown elements
    $("#value-" + sel1Value + "-" + sel2Value).show();
});

Check out the demo here: http://jsfiddle.net/b7Q8s/18/

Answer №2

Give it a shot

let $divElements = $('div[id^="value-"]').hide();

let $selector1 = $('#sel1').one('change', function(){
    $selector2.prop('disabled', false);
});
let $selector2 = $('#sel2');

$selector1.add($selector2).change(function(){
    let parameter1 = $selector1.val().replace(/\D+/, '');
    let parameter2 = $selector2.val().replace(/\D+/, '');
    $divElements.hide();
    $('#value-' + parameter1 + '-' + parameter2).show();
})

Check out the live demonstration here: Fiddle

Answer №3

My suggestion is to use the following code for a more precise selector:

// Adding an event handler for when a select element changes
$('select').change(function(){
    // Creating the id of the relevant element to show 
    var selectedValues = $('select option:selected').map(function(){
        return this.value.replace(/\D+/g,'');
    }).get().join('-');
   
    // Showing the relevant element and hiding its siblings
    $('#' + 'value-' + selectedValues).show().siblings().not('select').hide();
}).change();

Check out the JS Fiddle demo here.

The code does not toggle the display of the second select element intentionally, as the first select will always have a selected option. References to jQuery methods used can be found below.

References:

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

The issue arises when the ng-hide directive fails to function properly due to the presence of a custom directive with the terminal option

Below is the code for my button: <button ng-hide="todo === 'add'" confirm-click ng-click="delete()">Delete</button> This is the directive implementation: (function(app) { app.directive('confirmClick', function(){ ...

Perform an AJAX request within a condition prior to executing the subsequent AJAX request

Within my database, I have two tables. When the submit button is pressed, I aim to insert a new trader into the trader table and retrieve the ID using laravel 5.2 by utilizing post ajax under certain conditions. Then, execute another post ajax for invoic ...

Switch out the content within a div upon selection

I'm currently working on a palette board project and facing some challenges when switching to a different theme. The initial page is set to have a Warm color palette, but I intend to alter this once the user clicks on the All theme option. Users wil ...

What is the best method for saving HTML form data into a Node JS variable?

I am facing an issue with setting the values of HTML form inputs onto my Node JS variables. In the JavaScript code below, I am struggling to assign values to the variables "hostname" and "port," which should then be concatenated to create a new variable ca ...

Tips for preventing the overwriting of a JSON object in a React application

I'm trying to compare two JSON objects and identify the differing values in the second JSON object based on a specific key. My goal is to store these mismatched values in a new JSON object. The current issue I'm facing is that when there are mult ...

Run code after all images have been rendered in vuejs

Is there a way to execute code after all images have loaded, specifically needing to set the scroll in a specific position? Using nextTick() processes the code before the images are loaded. The mounted and created methods can't be used since the code ...

Enable AJAX functionality on dynamically created elements without needing to refresh the page

Although this question may have been asked in similar ways before, I am unable to identify the cause of the problem in my specific code. The issue is with a button that is supposed to toggle between "Add" and "Remove". When successful removal occurs, the ...

Is it feasible to determine the specific memory address of an Object in a program?

Is it possible in JavaScript to determine the memory location and memory usage of an object? Any assistance on this matter would be greatly appreciated. ...

The error message "TypeError: Cannot read property 'then' of undefined" is commonly seen in Promises and Express 4.x

[UPDATE] I encountered an issue while attempting to incorporate the promise, resulting in the following error message: TypeError: Cannot read property "then" of undefined getResult(options1).then(function(body){... let options1 = {...}; app.post("/web ...

Console is displaying an error message stating that the $http.post function is returning

Just diving into angular and I've set up a controller to fetch data from a factory that's loaded with an $http.get method connecting to a RESTful API: videoModule.factory('myFactory', function($http){ var factory = {}; facto ...

Storing each item in its own document within a Firebase collection

I have a feature where users input their sitemap and it generates all the links in the sitemap. How can I then store each of those links in separate documents within a specific collection on Firebase? Below is the current function used to set data in Fir ...

Removing a class with JQuery using the Contains method

I am attempting to remove the "hasChild" class from the following element, <li class="theme-nav-item selected enabled hasChild" data-nav-url="http://www.removed.com/page/nav/3353642"></li> by specifically targeting the value 3353642 with the ...

Testing an Express application using Jenkins

After spending hours searching for a way to execute my Mocha unit tests in Jenkins for my Express JS application, I am still struggling to find a solution. While writing the tests themselves is relatively easy, integrating them with my app has proven to b ...

Tips for establishing communication between a React Native webView and a React web application

I am currently working on establishing communication between a webView in react-native and a web-app created with React-360 (and React). I am utilizing the react-native-webview library and following a guide for creating this communication. You can find the ...

What is causing gog.com to malfunction when accessed through chromedriver?

Can you figure out why the appearance of gog.com differs between Google Chrome (left) and Chromedriver (right)? https://i.sstatic.net/m08Jh.jpg It's noticeable that things appear distorted and broken in Chromedriver. Even after comparing the two HTM ...

Typescript is experiencing an error due to the use of attr("disabled", false) causing a disruption

Within my ts file, I'm using the code snippet below: $('input[type=hidden]').attr("disabled", false); The code functions as intended, however, an error persists: Argument of type 'false' is not assignable to parameter of typ ...

connecting elements in an object's array to another array within a nested object

Is there a way to iterate through each string value in the imageKeys array and use it to create a URL for each object in the images array within the nested ImageList object, all without changing the original object? const myInitialStateFromParent = { ...

Setting an action when clicking on a slice of a Doughnut chart using Chart.js

I have been working on integrating chart.js into my Django Project, and so far it has been going smoothly. I successfully created a doughnut chart with two slices. Now, I am trying to implement separate actions for each slice when clicked, such as redirect ...

Trigger the click() event in jQuery before the blur() event

Looking to implement autocomplete suggestions in an input field? Take a look at the code below: <input type="text" id="myinput"> <div id="myresults"></div> To hide the results' div on the input's blur event, you can use this c ...

Discover the steps to traverse through directories and their numerous subdirectories (including a whopping 15000 subdirectories) with the help of the directory-tree

We are currently utilizing the directory-tree npm package to access and read through all directories and subdirectories, noting that there are as many as 15000 nested subdirectories. Code snippet in use: const dirTree = require("directory-tree"); const ...