Steps for creating a functional dropdown menu using list items and retrieving the selected values

I am looking to implement a feature with multiple drop-down menus using list items. The functionality I desire is that when the user clicks on a ul element, the list items should drop down. Then, upon clicking on a specific list item, the value of that item should replace the placeholder value in the existing list.

I came across a helpful code snippet that demonstrates this behavior, but I am having trouble implementing it in my CodePen project.

As I am not very experienced in JavaScript, I would greatly appreciate any guidance you can provide.

Is there a way to make my code behave like a standard select tag? I have chosen not to use the select tag due to the custom styling requirements that are not possible with select and option tags.

$(document).ready(function() {
  $("ul.which-way").on("click", function() {
    $(this).find('li').toggleClass("open-list");
    $(this).find('open-list').css("display", "block");
  });
  $("li.cadja").on("click", function() {});
});
.which-wrapper {
  width: 100%;
  max-width: 300px;
}

ul.which-way {
  margin: 0;
  list-style: none;
  background-color: grey;
  margin-bottom: 5px;
}

ul.which-way li:not(:first-child) {
  display: none;
}

ul.which-way {
  cursor: pointer;
  padding: 0;
}

li.open-list {
  display: block !important;
}

.find {
  margin-bottom: 10px;
  display: inline-block;
  width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="which-wrapper">
  <div class="drowpdown-one dropdown">
    <ul class="which-way">
      <li class="which-init">Unguided I-Day Return Trips</li>
      <li data-value="value 2" class="cadja"><span class="value">darling-wine-hops-day-by-which-way</span>Darling Wine & Beer Trip</li>
      <li data-value="value 3" class="cadja"><span class="value">mamre-werf-khwa-ttu-culture-day-by-which-way-trips</span>Culture & Adventure Trip</li>
      <li data-value="value 4" class="cadja"><span class="value">cape-west-coast-wildlife-fossil-trip</span>Wildlife & Fossils Trip</li>
    </ul>
    <a href="#" id="trip" class="find">FIND YOUR TRIP</a>
  </div>

  <ul class="which-way">
    <li class="which-init">Unguided I-Day Return Trips</li>
    <li data-value="value 2"><span class="value">darling-wine-hops-day-by-which-way</span>Darling Wine & Beer Trip</li>
    <li data-value="value 3"><span class="value">mamre-werf-khwa-ttu-culture-day-by-which-way-trips</span>Culture & Adventure Trip</li>
    <li data-value="value 4"><span class="value">cape-west-coast-wildlife-fossil-trip</span>Wildlife & Fossils Trip</li>
  </ul>
  <a href="#" id="trip" class="find">FIND YOUR TRIP</a>
</div>
</div>

Answer №1

To achieve the desired functionality, consider adding support for older IE versions (7/8) by detecting IE and using textContent in your code snippet:

$(document).ready(function(){
      $("ul.which-way").on("click", function() {
            $(this).find('li').toggleClass("open-list");
          $(this).find('open-list').css("display", "block");
      });
      $("li.cadja").on("click", function(){
          // Log the selected element's text
          console.log(this.innerText);
          // Find the parent element, locate 'which-init', and replace the text accordingly
        this.parentElement.getElementsByClassName('which-init')[0].innerText = this.innerText;
      });
});

Hopefully, this explanation clarifies the approach. The implementation is jQuery-based, hence appears slightly different:

$(document).ready(function(){
      $("ul.which-way").on("click", function() {
            $(this).find('li').toggleClass("open-list");
          $(this).find('open-list').css("display", "block");
      });
      $("li.cadja").on("click", function(){
          // Log the element's html on click
          console.log($(this).html());
          // Locate the parent element, find 'which-init', and update its content with all spans 
          $($(this).parent().find('.which-init')[0]).html($(this).html());
        // Convert the selected element to a jQuery object and log its value
        console.log('the value from onClick: ', $($(this).find('span.value')[0]).text());
        // Perform actions based on the value, e.g., calling a handler for dropdown-one
        handleDropdownOne();

      });  
});

// For demonstration purposes
window.handleDropdownOne = function() {
  // Log the value if something is selected in the first dropdown (ugly selector used)
  var dropOneValue = $($($('.drowpdown-one').find('.which-init')[0]).find('span.value')[0]).text();
  console.log('from handleDrpdownOne function: ', dropOneValue);
};

// Initialize the function, currently undefined
handleDropdownOne();

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

Enhancing Tapestry Grid component column sort icons

In the Tapestry Grid components, the default column sort icons are blue and white, but if your page has a different color scheme, you may want to personalize them. How can you replace the default Tapestry Grid column sort icons with your own custom icons? ...

Determining the optimal number of rows and columns based on an integer value

Here's a brain teaser for you: /** * Let's figure out the optimal number of rows and columns for your garden to be as square as possible, based on the number of seeds you have. * * @param {number} seedCount - The total number of seeds in you ...

Adjust size of background image to fit within ie8 window dimensions

Currently, I'm facing an issue where a Drupal 7 module is used to load a background image, but CSS3 resizing is not supported in IE8. background-image: url('image.jpg'); background-size: cover; I have tried conventional methods like placin ...

Increase the value of a property within an array of objects based on certain conditions

My task involves incrementing the rank value by one until the name property changes. I am utilizing the page and rank properties to track when this change occurs. In addition, I want to increment it once whenever the type is not equal to none, and then re ...

Updating information on <element>

Having trouble with the <object> element. I'm trying to display different external pages, but it's not functioning properly. It seems like once I set the data for the first time, any subsequent changes have no effect. Do I need to refresh i ...

How should Hyphenopoly be properly implemented?

I am encountering difficulties while trying to integrate Hyphenopoly into a Django project. The functionality sometimes works smoothly, but other times it does not. Additionally, when viewed on a mobile browser, the hyphenation appears inconsistent or even ...

Aligning text vertically to the top with material UI and the TextField component

Seeking guidance on adjusting vertical alignment of text in <TextField /> const styles = theme => ({ height: { height: '20rem', }, }); class Foo extends React.component { ... <TextField InputProps={{ classes: ...

Issue with ESlint global installation in macOS root terminal

Having trouble installing ESlint globally on my Mac running Mojave 10.14.6. Every time I try to run 'npm install -g eslint' I keep encountering this error: Your operating system has rejected the operation. npm ERR! It seems that you lack the nec ...

A guide to sketching the ellipsoid with three.js

Despite Three.js offering functions for drawing ellipses, I am in need of assistance to draw an ellipsoid instead. Can someone please help me? I have a specific requirement to draw an ellipsoid using three.js. ...

One of the great features of Next.js is its ability to easily change

At the moment, my dynamic path is configured to display events by their ID [id].js localhost:3000/event/1 But I would like it to be structured as follows: localhost:3000/city/date/title. All of this information is available in the events database, but I&a ...

Troubleshooting issues with the Select List component in ReactJS

Having an issue with the select list as the onChange event is not triggering. Struggling to set the selected value from the list in the this.state variable. Any assistance on this matter would be greatly appreciated. class SelectActivity extends React.C ...

Problems Arising from the Combination of Django and External JavaScript

I am currently working on a project that uses Django 1.11 and JavaScript, but I am encountering an issue. The JavaScript code works fine when run within the HTML file, as it successfully loads the JSON data. However, when I move everything to the static fo ...

What steps can be taken to ensure that a function is executed in order to delegate the process forward?

In my JavaScript code, I have a series of functions that need to be executed in a specific order. One function may return a value synchronously, while others do not return anything or return an Observable result asynchronously. How can I ensure that each ...

Script function in Google Sheets HTML not being called

Within my Google app, I have the following HTML code that is supposed to call a function below. However, I am not getting any response. This script has been used consistently throughout my code until now. <div id= "right_column"> <p> ...

Missing table header in HTML causing table to not display correctly

I currently have an HTML table that consists of three columns and a varying number of rows, depending on the output from a database. var fields = ['a','b','c']; //variable from database var data = ['p', & ...

Hide the div once it goes off screen, ensuring that the user stays in the same position on the page

On my website, I implemented an effect similar to the Airbnb homepage where there is a "How it Works" button that toggles a Div element pushing down the entire page. However, when the user scrolls to the bottom of the toggled div (#slideDown) and it disapp ...

Loading objects with textures in Three.js using the objloader

For the past few weeks, I've been diving into Three.js and managed to successfully apply a texture to a cube I created directly in the code. However, when I attempted to load an OBJ file using OBJLoader, I ran into issues trying to load simple png or ...

What are some ways to reuse an angular component multiple times?

I am utilizing an angular component to dynamically load charts into my widget: Below is an example of the component: angular.module("generalApp").component("chartPie", { template: "<div class=Pie></div>", bindings: { data: "=", }, control ...

Tips for guaranteeing blocking within a loop in Node.JS

While I usually enjoy the asynchronous nature of Node.JS and its callback-soup, I recently encountered an issue with SQLite that required a certain part of my code to be run in a blocking manner. Despite knowing that addressing the SQLite problem would mak ...

Navigating through vuetify's v-select internal stateHow to bypass vuetify's v-select

How can I prevent a value from being 'selected' when using the vuetify's v-select component? Here is an example: <v-checkbox v-model="allowChanges" ></v-checkbox> <v-select v-model="twoWayComputed" :items="items" ...