Display the <select> options panel in the form of an accordion instead of a dropdown menu

Hello, I am attempting to display a list of tag options as an accordion instead of a dropdown menu, but unfortunately, it's not working the way I want it to.

Here is what I have:

<select onclick="document.getElementById('options');" onChange="accordion(this.value)" name="search_type" style="margin-right:10px; margin-top:2px;" class="button-white">

<div id="options">
    <option selected="selected" value="Precipitación">Precipitación +</option>    
    <option value="veggies_search">Humedad</option>
    <option value="animals_search">Precipitación</option>
    <option value="all_search">Presión Atmosférica</option>
    <option value="all_search">Temperatura</option>
    <option value="all_search">Velocidad Viento</option>
</div>

  </select>


<script type="text/javascript">
  function accordion(value){

  }
</script>

I am using the select tag because I need the name of the selected option to be displayed on the trigger button.

function accordion(value){
    
}
<select onclick="document.getElementById('options');" onChange="accordion(this.value)" name="search_type" style="margin-right:10px; margin-top:2px;" class="button-white">
    
<div id="options">
    <option selected="selected" value="Precipitación">Precipitación +</option>    
    <option value="veggies_search">Humedad</option>
    <option value="animals_search">Precipitación</option>
    <option value="all_search">Presión Atmosférica</option>
    <option value="all_search">Temperatura</option>
    <option value="all_search">Velocidad Viento</option>
</div>

  </select>

I would appreciate any assistance you can offer. Thank you very much.

Answer №1

A div element cannot be a direct child of a select element. To achieve the desired functionality, you will need to utilize div elements along with JavaScript. Here is an example solution:

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
    acc[i].addEventListener("click", function() {
        /* Toggle between adding and removing the "active" class,
        to highlight the button that controls the panel */
        this.classList.toggle("active");

        /* Toggle between hiding and showing the active panel */
        var panel = this.nextElementSibling;
        if (panel.style.display === "block") {
            panel.style.display = "none";
        } else {
            panel.style.display = "block";
        }
    });
}

var options = document.getElementsByClassName("option");

for(var o = 0; o < options.length; o++) {
  options[o].addEventListener('click', function(e) {
  this.parentElement.previousElementSibling.innerHTML = this.dataset.value;

    /* alert(e.target.dataset.value);  */
  })
}
/* Style the buttons used for opening and closing the accordion panel */
.accordion, .option  {
    background-color: #eee;
    color: #444;
    cursor: pointer;
    padding: 18px;
    width: 100%;
    text-align: left;
    border: none;
    outline: none;
    transition: 0.4s;
    font-family: Arial, sans-serif;
    font-size: 11px;
}

.active, .accordion:hover, .option:hover {
    background-color: #ccc;
}

.panel {
    padding: 0 18px 0 0;
    background-color: white;
    display: none;
    overflow: hidden;
}

.option {
  padding: 9px 18px;
}
<button class="accordion">Precipitation +</button>
<div class="panel">
  <div class="option" data-value="Humidity">Humidity</div>
  <div class="option" data-value="Atmospheric Pressure">Atmospheric Pressure</div>
  <div class="option" data-value="Temperature">Temperature</div>
  <div class="option" data-value="Wind Speed">Wind Speed</div>
</div>

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 React state (array) to be empty within a callback function? Why is it failing to utilize the latest value from the external

I'm facing a challenge that has me stumped. I am attempting to add values to an existing array, but for some reason, the 'state' variable is always empty inside the onmessage callback function. I can't seem to figure out why this is hap ...

Incorporating a jQuery word count and limit within PHP code: a step-by-step guide

I am encountering an issue with a textarea count code. It functions perfectly on its own but when I integrate it as shown below, it stops working without throwing any errors. I have been trying to resolve this for more than 3 days now. Any assistance would ...

Steps to duplicate a Select input and attach it to a div using Jquery

Recently, I was working on a Select input with the name "item" as an example. <select name="item"> <option value="1">1</option> <option value="2" selected="selected">2</option> <option value="3">3</option> <opt ...

Struggling with transferring values from PHP to AJAX

I'm experiencing an issue with the interaction between AJAX and PHP. Despite trying various solutions found in similar questions and answers, none seem to be working for me. The goal of this code is to retrieve a JSON string from a PHP file hosted on ...

Issue with knockout view - unable to remove item from view after deletion

I'm facing an issue with my code that deletes an exam from a list of exams on a page, but the deleted exam still shows up until the page is manually refreshed. This pattern works correctly on other pages, so I don't understand why it's not w ...

Issue encountered when using the jQuery tokeninput plugin: difficulty when retrieving search results containing a single character digit

Has anyone ever used the jquery tokeninput plugin for tag autocompletion? I'm experiencing an issue where when I type the first character in the search input, the search functionality works correctly and returns results. However, the dropdown autocom ...

Utilizing AJAX and JQuery to Load KML Data

Attempting to integrate a KML layer into Google Maps API 3.0 using a JQuery AJAX request. Here is the current code setup (currently not functioning). <script> $(document).ready(function(){ $.ajax({ url : 'https://blahhhhhhhhhh.com/KML_Pla ...

Customizing default elements in A-frame: Tips and Tricks

One of the default components attached to an A-frame entity is rotation and position. I am looking to customize these components and apply the changes to the entities. For instance, I would like to create a new component called "positionnew" with a differ ...

Creating dynamic dropdown lists that automatically apply the active class to the chosen option

Here is the JSTL tags code I am using: <ul class="megamenu skyblue"> <!--1st level of categories --> <c:forEach var="item1" items="${shoppingCart.categories}"> <li id="headerCategory" class="grid" style="border-right: 1px solid # ...

Generating an Array of Meshes Using Objects in THREE.JS and GLTF Format

Here is the code snippet I have for loading a mesh onto an object. Currently, it is iterating through the entire mesh. Code snippet: var loader = new THREE.GLTFLoader(); loader.load( '../gtf/Box.gltf', function ( gltf ) { ...

Tips for embedding a script into an HTML document

I've been experimenting with tinymce npm and following their guide, but I've hit a roadblock. Including this line of code in the <head> of your HTML page is crucial: <script src="/path/to/tinymce.min.js"></script>. So, I place ...

Identifying the conclusion of a lengthy request in NodeJS/Express

Currently grappling with Server-sent events, my pseudo-code setup involves the following: var listeners = []; app.get('/stream', function (req, res) { listeners.push({ req: req, res: res }); }); // ... some action takes place notify(listene ...

What methods can be used to pause a jQuery function when hovering and resume it when the mouse leaves?

I'm currently working on a jQuery function that operates on the mousemove event. The goal is to have two images - one main image and one shadow image, with the shadow image reflecting movement based on mouse position. While everything is functioning p ...

Struggling to deploy my Laravel application with Tailwind CSS on the frontend. However, running "npm run dev" results in an error

While running the npm command `npm run dev` in cmd, I encountered an error stating that I require PostCSS v8 even though I already have PostCSS v8.3 installed. Could it be possible that Tailwind CSS specifically needs version 8 despite newer versions being ...

Transforming a select dropdown from multiple selection to single selection

Trying to create a scenario where the second dropdown menu in my HTML changes based on the selection from the first dropdown. If "Multiple" is selected in the first dropdown, then the second dropdown should have the attribute multiple="multiple". If "Singl ...

Combining ASP.NET with jQuery to create dynamically generated HyperLink controls

My ASP.NET application includes HyperLink elements that are dynamically generated based on database values. When a user clicks one of these links, a jQuery dialog box appears for editing. The issue arises when trying to save the modified values back to the ...

Enhancing the appearance of standard HTML checkboxes

This HTML snippet displays a pair of checkboxes positioned side by side <div id="mr_mrs"> <ul class="mr_mrs form-no-clear"> <li id="mr" class="popular-category"> <label for="Mr" id="mr">Mr</label> ...

Explore the wonders of generating number permutations using JavaScript recursion!

After providing the input of 85 to this function, I noticed that it only returns 85. I am confused as to why it is not recursively calling itself again with 5 as the first number. console.log(PermutationStep(85)); function PermutationStep(num) { var ...

A guide to utilizing asynchandler within a class in Node.js

I'm currently in the process of converting my routers into a class structure, but I'm facing a challenge when trying to wrap the asyncHandler function inside the class. Can anyone provide guidance on how to achieve this? userController.js const ...

Struggling to activate the .tab function in Bootstrap 4

I am attempting to trigger the opening of a tab programmatically in my code using swipe gestures. However, I am encountering an issue where calling .tab('show') does not have any effect and does not produce any errors. Below is the code snippet: ...