Transforming divs into a dropdown to mimic the functionality of a select or combo

I have multiple divs contained within a wrapper div, each representing the same entity as shown in image 1.

https://i.sstatic.net/iNjqB.jpg

When I click on "Select 1" or "Select 2", I need to trigger a dropdown list that allows me to select an option and change the value of the corresponding Select element. The design of this dropdown list should match the look of the Select div items, as seen in image 2.

https://i.sstatic.net/JfUb2.jpg

I have explored numerous jQuery select plugins without success. Can anyone provide guidance on how to achieve this functionality or recommend a plugin that can help with this task?

The following is the HTML code snippet:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>test</title>
        <meta charset="utf-8">      
        <style>
            .wrapper
            {
                width:330px;
                overflow:hidden; 
                border:solid 1px gray; 
                padding: 3px;                
            }
            .element
            {
                width:80px; 
                min-height: 30px; 
                border:solid 1px black; 
                background-color: orange; 
                text-align: center;
                line-height: 30px;                
            }
            .float-left
            {
                float: left;
            }            
        </style>
    </head>
    <body>
        <div class="wrapper">
            <div class="element float-left">
                Select 1
            </div>
            <div class="element float-left">                
                Select 2                
            </div>
            <div class="element float-left">
                Select 3
            </div>            
            <div class="element float-left">
                Select 4
            </div>            
        </div>

    </body>
</html>

Thank you for your assistance.

Answer №1

Check out this helpful tutorial on creating a simple CSS dropdown menu without JavaScript: Simple Dropdown

For those interested in opening the dropdown through jQuery, follow these steps:

Firstly, remove the following CSS code from my example:

 .main_nav > li:hover .sub_nav{
        background-color:#E4E4E4;
        display:block;
    }

Instead, utilize jQuery with the following code snippet:

    $(".main_nav > li").click(function(){
           $(' .sub_nav').show();
          $(this).find('.sub_nav').show();
   });

Answer №2

Are you familiar with the Jquery libraries? Take a look at this demo for some inspiration. Feel free to make adjustments to suit your needs.

 <style>
    .wrapper
    {
        width:330px;
        overflow:hidden; 
        border:solid 1px gray; 
        padding: 3px;                
    }
    .element
    {
        width:80px; 
        min-height: 30px; 
        border:solid 1px black; 
        background-color: orange; 
        text-align: center;
        line-height: 30px;                
    }
    .float-left
    {
        float: left;
    }            
</style>

<div class="wrapper">
    <div class="element float-left">
        Select 1
    </div>
    <div class="element float-left">                
        Select 2
        <div class='options'>
            <div class='element'>Option 1</div>
            <div class='element'>Option 2</div>
            <div class='element'>Option 3</div>
            <div class='element'>Option 4</div>
        </div>                
    </div>
    <div class="element float-left">
        Select 3
        <div class='options'>
            <div class='element'>Option 1</div>
            <div class='element'>Option 2</div>
            <div class='element'>Option 3</div>
            <div class='element'>Option 4</div>
        </div>  
    </div>            
    <div class="element float-left">
        Select 4
    </div>            
</div>
<script type="text/javascript">
$(document).ready(function(){
    $(".options").slideUp(0);
    $(".element").click(function(){
        $(".options").hide(0);
        $(this).find('.options').slideDown(100);
    });

});
</script>

Answer №3

While I may not be a fan of jQuery, here is a pure JavaScript solution that might interest you. It's still a work in progress and may throw some errors, but feel free to customize it according to your needs.

var Ready = function(){
  var menu = document.querySelector('.wrapper');
  var elementsList = menu.querySelectorAll('.container');
  var toggleSubmenu = function(e){
    var current = e.target.parentNode.querySelector('.submenu');
    for(var i=elementsList.length; i--;){
      var element = elementsList[i].querySelector('.submenu');
      if (element!==current && element.classList.contains('opened'))
        element.classList.remove('opened');
    }
    current.classList.toggle('opened');
  };
  menu.addEventListener('click', toggleSubmenu);
};
document.addEventListener( 'DOMContentLoaded', Ready );
.wrapper {
  width: 330px;
  overflow: hidden;
  border: solid 1px gray;
  padding: 3px;
  cursor: pointer;
}
.select, .option {
  width: 80px;
  min-height: 30px;
  border:solid 1px black;
  background-color: orange;
  text-align: center;
  line-height: 30px;
  position: relative;
}
.container {
  float: left;
}
.submenu {
  position: absolute;
  height: 0;
  overflow: hidden;
}
.opened {
  height: auto;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Test</title>
</head>
<body>
  <div class="wrapper">
     <div class="container">
        <div class="select">Select 1</div>
        <div class="submenu">
          <div class="option">Option 1</div>
          <div class="option">Option 2</div>
          <div class="option">Option 3</div>
        </div>
     </div>
     <div class="container">
        <div class="select">Select 2</div>
        <div class="submenu">
          <div class="option">Option 1</div>
          <div class="option">Option 2</div>
          <div class="option">Option 3</div>
        </div>
     </div>
     <div class="container">
        <div class="select">Select 3</div>
        <div class="submenu">
          <div class="option">Option 1</div>
          <div class="option">Option 2</div>
          <div class="option">Option 3</div>
        </div>
     </div>
     <div class="container">
        <div class="select">Select 4</div>
        <div class="submenu">
          <div class="option">Option 1</div>
          <div class="option">Option 2</div>
          <div class="option">Option 3</div>
        </div>
     </div>
  </div>
</body>
</html>

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

Filtering Gridviews with Javascript or jQuery

My current project involves using an ASP.NET GridView with multiple ListBoxes representing Departments, Categories, Faculties, and more. The data in these ListBoxes and the GridView is dynamically loaded from a MSSQL database in the codebehind. I am in ne ...

Ways to distinguish XmlHttpRequest Access-Control-Allow-Origin issues from regular network errors

When making an ajax request, there is a possibility of encountering an error, indicating a failure to establish communication with the intended target (no status code returned). To handle these errors, you can use the following code: var oXhr = new XMLHt ...

How can I retrieve PHP code output within a jQuery function?

In my CodeIgniter project, I am trying to generate a unique ID using PHP by calling the random_string() function: function coding(){ echo random_string('unique'); } I want to use the result of this function in an AJAX jQuery call (to be use ...

What could be causing the issue with the <bgsound src="music/binks.mp3"/> not functioning properly?

Looking to add some background music to my website, but struggling to find current information after searching for 15 minutes. Can anyone provide assistance? <body> <bgsound src="music/binks.mp3"/> </body> <bgsound src=& ...

What causes Angular projects to only display a single object when using an array?

I've been exploring the League of Legends API, specifically focusing on the champion json data it provides. Currently, I have developed a service using Angular: import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders} f ...

Ways to organize an array based on various characteristics

I am seeking assistance regarding grouping in Javascript. Below is an array where each item has either is_sweet, is_spicy, or is_bitter set to true: const foodsData = [{ name: 'mie aceh', is_sweet: false, is_spicy: true, ...

Performing multiple asynchronous tasks using RxJS by running Array.prototype.map in parallel batches or queues

Imagine having an array of variables, such as: [Sasha, Misha, Caitlyn, ...String] (string[]) with a sizable length of about 10k elements. If you want to run an asynchronous parallel task with these elements, but not all at once like Promise.all, rather in ...

Could someone please help me identify the mistake in this code? I recently created a new class, imported it into a .ts file, and then proceeded to define

Upon checking the console, an error message appeared stating that Recipe was not defined. To resolve this issue, I made sure to include the necessary class definition in a separate file at the end of my code. The import statement: import { Recipe } from ...

The response from Ajax displays PHP text on the response page

This snippet shows my AJAX code in the view file $('#bidck').click(function (e) { e.preventDefault(); var data = "ajax=ajax"; $.ajax({ type: 'POST', url: 'http://localhost:8080/test/check', ...

Opening a document with `document.open` will clear all event listeners

I've developed a Chrome extension that records user behavior while browsing web pages by adding event listeners to customers' web pages using a Chrome content script. The code in the content script looks something like this: var recordingEvents ...

Alert: It is not possible to update the React state on a component that is already unmounted after updating the context and switching to a different page

I am facing a challenge that requires your assistance In the /editpage, there is a changeProfile function that should be triggered upon clicking const appContext = useContext(AppContext); const [userLogin, setUserLogin] = appContext.userLogin; const [use ...

Utilizing Regular Input with Material-UI's Autocomplete Feature

Is there a way to replace TextField with a regular input in an Autocomplete? ...

What is the best method for selecting only files (excluding folders) in Gulp?

I have a gulpfile where I am injecting files into an appcache manifest in this manner: var cachedFiles = gulp.src('**', {read: false, cwd: 'build'}); gulp.src('src/*.appcache', {base: 'src'}) .pipe($.inject(cachedF ...

What is the best way to ensure that text only displays up to five lines and fully collapses using CSS or javascript/jquery?

Hello everyone, I have come across an issue. English is not my strong suit, but I will do my best to explain it thoroughly. The problem at hand is a design requirement in the draft that specifies showing up to five lines of text. If the text exceeds this ...

Leveraging the power of Javascript and Firebase within the Angular framework

When attempting to integrate Firebase with Angular, I encountered an issue where my localhost was not able to function properly with my JavaScript code. The strange thing is that everything works fine when the code is placed directly in the index.html file ...

How can we incorporate spans into child elements using JavaScript?

Recently, I encountered a problem with a code that is supposed to add a span if it doesn't already exist on certain elements. However, the current implementation only adds the span to one element and not others because the code detects that it already ...

Is it possible for you to enter "1.00" instead of just 1 when using the input type as number?

I am using Polymer paper-input and I would like to ensure that my input with type "number" always displays 2 decimal points, even when it is a whole number. Instead of just displaying as "1", I want it to be shown as "1.00" at all times. I have tried sett ...

Using getJSON to call the Controller in .cshtml

I successfully executed this action in a .js file without any complications, but now I'm facing difficulties implementing it in a .cshtml file. Despite thorough investigation, I can't identify any other potential reasons for this failure. Below i ...

Switching the default z-index for child elements within an HTML container

According to the specification, elements are typically drawn "in tree order" for in-flow, non-positioned elements of similar block level or float status and identical z-index. This means that elements declared last in the HTML markup appear on top. But wha ...

The Node JS API remains unresponsive when the request parameters are increased, continuing to send multiple requests to the server without receiving

Using the API below returns nothing: http://localhost:6150/api/v1/simpleSurveyData/abc/:projectId/:startDate/:endDate/:visitMonth However, if I remove any of the four parameters or provide less than four parameters, and adjust the API route in Node.js acc ...