Toggle visibility of a div based on a dropdown option using the getElementsByClassName method

Seeking assistance for switching style properties of divs based on selection from a select menu. Any guidance would be appreciated!

Here is the code:

The select tag (where I pass the value to the script function):

<div style="float: right; margin-right: 5%; width: auto;">
    <select style="border: 3px intset; border-radius: 5px; border-color: #17FFFF;" onchange="showstuff(this.value);">
        <optgroup label="Lisboa">
            <option value="Picoas">Picoas</option>
            <option value="Benfica">Benfica</option>
        </optgroup>
        <optgroup label="Porto">
            <option value="Felgueiras">Felgueiras</option>
            <option value="Maia">Maia</option>
        </optgroup>
    </select>
</div>

The divs with the class names:

<div style="width: 90%; height: 50%; background-color: #09C; overflow: scroll; overflow-x: hidden; margin-bottom: 15%; margin-left: 5%; margin-right: 5%; text-align: left; color: #000; font-size: 60%;">
    <div class="Picoas" style="height: 30%; width: 100%; background-color: #CCEAFF; display:none;">
        Timberland Picoas<br />
        Centro Colombo Morada: Av. Lusíada, Centro Colombo Piso 1, Loja 1.095<br />
        1500-392 Lisboa
    </div>
    <!-- More div elements here with different classes and content -->
</div>

The script and class definitions:

<script type="text/javascript">
function showstuff(element) {
    var elementsPicoas = document.getElementsByClassName("Picoas");
    elementsPicoas.style.display = element == "Picoas" ? "block" : "none";
    // Repeat this block for other classes like Benfica, Felgueiras, Maia
} 
</script>
<style>
.Picoas{}
.Felgueiras{}
.Benfica{}
.Maia{} 
</style>

Answer №1

Learn how to achieve this without using jQuery!

function revealContent(chosenElementClass) {

    var elementClasses = [
        "Marques",
        "Porto",
        "Braga",
        "Guimaraes"
    ];

    for (var i = 0; i < elementClasses.length; i++) {
        var elements = document.getElementsByClassName(elementClasses[i]);

        for (var j = 0; j < elements.length; j++) {
            var element = elements[j];
            element.style.display = (element.className === chosenElementClass)? "block" : "none";
        }
    }
} 

Check out it in action here:

Answer №2

If you're looking for a solution to hide and show elements dynamically, consider using jQuery. Here's an example:

$(".Tokyo, .Osaka, .Kyoto, .Hiroshima").hide(); //hide all
$("." + element).show(); //display only the selected one

Update

Upon closer inspection, it seems like the issue lies in the getElementsByClassName function returning multiple elements due to repetitive class declarations. To tackle this without jQuery, try the following approach:

function display(className, mode)
{
    var elements = document.getElementsByClassName(className);

    for (var i = 0; i < elements.length; i++)
    {
        elements[i].style.display = mode;
    }

}

function showElement(element) 
{
    //hide all elements
    var allElements = ["Tokyo", "Osaka", "Kyoto", "Hiroshima"];

    for (var i = 0; i < allElements.length; i++)
    {
        display(allElements[i], "none");
    }

    //display the selected element
    display(element, "block");
} 

Answer №3

A more streamlined approach using jQuery:

<script type="text/javascript>
$(document).ready(function(){
   $("#selectOption").change(function(){
     $(".dynamicContent").css("display", "none");
     $("."+this.value).css("display", "block");
   });
});
</script>

<style>
.dynamicContent
   {
       height: 50%; 
       width: 80%; 
       background-color: #F6E3FF; 
       margin-top: 5%;
       display:none;
   }
.option1{}
.option2{}
.option3{}
.option4{} 
</style>

<div class="option1 dynamicContent">
    Option 1 Details here<br />
    Address: 123 Main Street, Anytown USA 12345<br />
</div>
<div class="option2 dynamicContent">
    Option 2 Details here<br />
    Address: 456 Elm Avenue, Another City XYZ ABC<br />
</div>
(etc.)

http://jsbin.com/awesome/78654/edit

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

Tips for selecting a specific input field in a ReactJS component with multiple inputs

I am currently developing a ReactJS application where I have implemented a component responsible for generating an HTML table. Within this component, I utilize Map to create rows using a child component. These rows contain multiple input fields that users ...

Exploring the possibilities of utilizing a Kendo grid within an ASP.NET Web API

I am currently using the open source edition of Kendo Web with the Kendo UI Web on ASP.NET MVC 4. My Kendo grid contains the following JavaScript code: <script> $(document).ready(function () { $("#grid").kendoGrid({ dataSource: ...

Exploring Kendo Pages with ID Navigation and Displaying Information

In my MVC project, I have two views. From View1, I am retrieving an ID and passing it to View2. In View2, I already have a KendoGrid set up with a controller that fetches data and displays it in the grid. My question is how can I access the data from the ...

What's preventing me from tapping on hyperlinks on my mobile device?

I'm currently working on a website (saulesinterjerai.lt) and everything seems to be functioning properly, except for the fact that on mobile devices, the links aren't clickable and instead navigates to other layers. How can I disable this behavio ...

Can we determine the drop location of an object in jQuery UI?

I am trying to determine the specific DOM element on a grid where an object was dropped, not just its x and y position. The grid is composed of div elements where various items can be dropped, and I need to identify the particular div where the item was dr ...

React-native horizontal sliding plugin

Can anyone recommend a reliable horizontal slider plugin for react-native? I've come across some options, but they haven't been working as smoothly as I'd hoped. ...

Can components be designed in a way that includes elements such as buttons or text areas in the code, but allows for them to be excluded when the component is used?

I have a custom form component that I designed. Depending on certain cases, I want the form to display either a button or a text field instead of the input field as currently coded. function FormTypeOne(props) { return ( <form className={classes.f ...

Error message thrown by a React custom hook: "Error: Queue is missing. This is probably a bug within React. Please report this issue."

In my React component, I need to utilize a custom React hook within the component. However, this hook should only be invoked when a specific feature toggle is enabled. I am aware that this approach may go against the rule of hooks as outlined here: https:/ ...

Best practice for showcasing the output of an array in Javascript

My variables are defined in an array like this: const nbActions = 13; const sdgValues = ['1', '2', '5', '6', '3', '0', '2', '0', '0', '6', '0', & ...

How can I retrieve the word that comes after a specific word in discord.js

Currently, I'm attempting to create a bot similar to Dad bot, but I'm struggling with implementing the "Hi __ I'm, Dad" feature. Here's the code snippet that I've put together so far: var imWords = ["i'm", "I&a ...

Creating a pop-up window displaying event details when a user hovers over or clicks on an event in fullcalendar using JavaScript

I have been struggling for a while now, attempting every possible way to add a popup window on mouse hover using fullcalendar. Sadly, all the solutions I've tried either mess up my calendar or don't work at all. I am trying to implement a popup w ...

Leverage the potential of the value parameter within a mongoose scope

I am currently trying to retrieve emails of a user based on their id. However, I have encountered an issue due to the asynchronous nature of the mongoose function. Mail.find({receiver_id: '#id#'}, function(err, mails) { var result = []; ...

How can pagination be implemented with a line chart in Chart.js?

I'm dealing with a large amount of data - around 10,000 rows that I need to display in a line chart. I'm looking for a pagination system where users can click on an arrow to show the next 20 data points, and so on. Currently, my app crashes when ...

What could be causing this code to malfunction when using D3.min version instead?

In this coding example, a scale and an axis object can be seen in the console: <!DOCTYPE html> <head> </head> <body> <script src="//d3js.org/d3.v5.js"></script> <script> console.log(d3.scale ...

Discovering the category to which $(this) belongs

I am attempting to target the class of the clicked button in order to create a generic event that will fade out all elements of the generic class "gen", excluding the elements that belong to the clicked button. $(document).ready(function(){ $(this).cl ...

I just obtained the height measurement of a dynamic table - now I must transfer this height value to a different element

Recently, I encountered a situation where I needed to get the height of a dynamic table using code like this: var table = document.getElementById("test"); document.write(table.offsetHeight); However, the challenge arose when I realized that I also needed ...

What is the process to gain entry to a Vue3 instance from another location in order to execute a specific function

Is there a way to access a Vue 3 instance when I am not aware of the variable name that holds this instance? I need to be able to execute a function from a specific component. Upon typing $0.__vue_app__ in the console (Chrome Developer Tools), I can see t ...

What sets $vm.user apart from $vm.$data.user in Vuejs?

When you need to retrieve component data, there are two ways to do so: $vm.user and $vm.$data.user. Both methods achieve the same result in terms of setting and retrieving data. However, the question arises as to why there are two separate ways to access ...

Question about using React, NPM, Vite, Babel, and Node.js together

I want to confirm my understanding. So, if I decide to create a react 'app' and incorporate babel for jsx support. Then, I opt for vite for enhanced development runtime and packaging. Lastly, I utilize node.js to execute my code. To sum it up, ...

Leveraging Firebug debugger to troubleshoot and resolve script conflicts

I had my website running smoothly until suddenly the hero image stopped loading and I started seeing an error message in the console saying "ReferenceError: imagesLoaded is not defined" in wine-cheese.js, followed by another error "Error: multipleDefine" i ...