What is the best method to retrieve the value from a chosen list item?

I decided to incorporate a horizontal selection menu from CodePen into my project, and you can find the source code here

Here is the outcome:

var btn = document.querySelector("button")
var dropdown = document.querySelector(".dropdown-options")
var optionLinks = document.querySelectorAll(".option a")
console.log(optionLinks)

btn.addEventListener("click", function(e) {
  e.preventDefault()
  console.log("btn")
  dropdown.classList.toggle("open")
});

var clickFn = function(e) {
  e.preventDefault()
  dropdown.classList.remove("open")
  btn.innerHTML = this.text
  var activeLink = document.querySelector(".option .active")

  if (activeLink) {
    activeLink.classList.remove("active")
  }
  this.classList.add("active")
}
for (var i = 0; i < optionLinks.length; i++) {
  optionLinks[i].addEventListener("mousedown", clickFn, false)
}
.container {
  max-width: 500px;
  margin-top: 10px;
  margin-left: 0px;
}
.container button {
  position: relative;
  background: none;
  border: none;
  outline: none;
  font-size: 16px;
  border-bottom: 2px solid #9b9b9b;
  padding-bottom: 8px;
  min-width: 150px;
  text-align: left;
  outline: none;
  cursor: pointer;
  z-index: 2;
}
.container button:after {
  content: '▾';
  position: absolute;
  right: 0px;
  top: 0%;
  color: rgb(142, 142, 142);
}
.container .dropdown {
  position: relative;
}
.container .dropdown .dropdown-options {
  list-style: none;
  margin: 0;
  padding: 0;
  background: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.24);
  display: inline-block;
  position: absolute;
  left: 0;
  bottom: 0;
  opacity: 0;
  -webkit-transform: scale(0.8) translate3d(-20px, 0px, 0);
          transform: scale(0.8) translate3d(-20px, 0px, 0);
  -webkit-transition: opacity 0.1s cubic-bezier(0.5, 2, 0.5, 0.75), -webkit-transform 0.3s cubic-bezier(0.5, 2, 0.5, 0.75);
  transition: opacity 0.1s cubic-bezier(0.5, 2, 0.5, 0.75), -webkit-transform 0.3s cubic-bezier(0.5, 2, 0.5, 0.75);
  transition: opacity 0.1s cubic-bezier(0.5, 2, 0.5, 0.75), transform 0.3s cubic-bezier(0.5, 2, 0.5, 0.75);
  transition: opacity 0.1s cubic-bezier(0.5, 2, 0.5, 0.75), transform 0.3s cubic-bezier(0.5, 2, 0.5, 0.75), -webkit-transform 0.3s cubic-bezier(0.5, 2, 0.5, 0.75);
  -webkit-transform-origin: 0 100%;
  transform-origin: 0 100%;
  z-index: 1;
}
.container .dropdown .dropdown-options.open {
  opacity: 1;
  -webkit-transform: scale(1) translate3d(0, 0, 0);
          transform: scale(1) translate3d(0, 0, 0);
  z-index: 5;
}
.container .dropdown .dropdown-options li {
  display: inline-block;
}
.container .dropdown .dropdown-options li a {
  text-decoration: none;
  display: inline-block;
  padding: 10px 16px;
  color: #2975DA;
}
.container .dropdown .dropdown-options li a:hover {
  color: #2269c7;
}
.container .dropdown .dropdown-options li a.active {
  border-bottom: 2px solid #9b9b9b;
  color: #9b9b9b;
}
.container .dropdown .dropdown-options li a.active:hover {
  color: #9b9b9b;
}
<div class="container">
  <div class="dropdown">
    <button>Type</button>
    <ul class="dropdown-options">
      <li class="option">
        <a href="#">A</a>
      </li>
      <li class="option">
        <a href="#">B</a>
      </li>
      <li class="option">
        <a href="#">C</a>
      </li>
      <li class="option">
        <a href="#">D</a>
      </li>
    </ul>
  </div>
</div>

I'm currently facing some challenges in retrieving the selected `li` element before submitting the form. Since it's not a `select` element and I've integrated this menu within a form, I was wondering if there's an easier way to fetch the selected value of `li` using JavaScript?

Answer №1

If you're looking for a solution, check out this link

var btn = document.querySelector("button")
var dropdown = document.querySelector(".dropdown-options")
var optionLinks = document.querySelectorAll(".option a")

btn.addEventListener("click", function(e) {
  e.preventDefault()
  dropdown.classList.toggle("open")
});

var clickFn = function(e) {
  console.log(e.target.innerText);
  e.preventDefault();
  dropdown.classList.remove("open");
  btn.innerHTML = this.text;
  var activeLink = document.querySelector(".option .active");

  if (activeLink) {
    activeLink.classList.remove("active");
  }
  this.classList.add("active");
}

for (var i = 0; i < optionLinks.length; i++) {
  optionLinks[i].addEventListener("mousedown", clickFn, false);
}
.container {
  max-width: 500px;
  margin-top: 10px;
  margin-left: 0px;
}
.container button {
  position: relative;
  background: none;
  border: none;
  outline: none;
  font-size: 16px;
  border-bottom: 2px solid #9b9b9b;
  padding-bottom: 8px;
  min-width: 150px;
  text-align: left;
  outline: none;
  cursor: pointer;
  z-index: 2;
}
.container button:after {
  content: '▾';
  position: absolute;
  right: 0px;
  top: 0%;
  color: rgb(142, 142, 142);
}
.container .dropdown {
  position: relative;
}
.container .dropdown .dropdown-options {
  list-style: none;
  margin: 0;
  padding: 0;
  background: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.24);
  display: inline-block;
  position: absolute;
  left: 0;
  bottom: 0;
  opacity: 0;
  -webkit-transform: scale(0.8) translate3d(-20px, 0px, 0);
          transform: scale(0.8) translate3d(-20px, 0px, 0);
  -webkit-transition: opacity 0.1s cubic-bezier(0.5, 2, 0.5, 0.75), -webkit-transform 0.3s cubic-bezier(0.5, 2, 0.5, 0.75);
  transition: opacity 0.1s cubic-bezier(0.5, 2, 0.5, 0.75), -webkit-transform 0.3s cubic-bezier(0.5, 2, 0.5, 0.75);
  transition: opacity 0.1s cubic-bezier(0.5, 2, 0.5, 0.75), transform 0.3s cubic-bezier(0.5, 2, 0.5, 0.75);
  transition: opacity 0.1s cubic-bezier(0.5, 2, 0.5, 0.75), transform 0.3s cubic-bezier(0.5, 2, 0.5, 0.75), -webkit-transform 0.3s cubic-bezier(0.5, 2, 0.5, 0.75);
  -webkit-transform-origin: 0 100%;
  transform-origin: 0 100%;
  z-index: 1;
}
.container .dropdown .dropdown-options.open {
  opacity: 1;
  -webkit-transform: scale(1) translate3d(0, 0, 0);
          transform: scale(1) translate3d(0, 0, 0);
  z-index: 5;
}
.container .dropdown .dropdown-options li {
  display: inline-block;
}
.container .dropdown .dropdown-options li a {
  text-decoration: none;
  display: inline-block;
  padding: 10px 16px;
  color: #2975DA;
}
.container .dropdown .dropdown-options li a:hover {
  color: #2269c7;
}
.container .dropdown .dropdown-options li a.active {
  border-bottom: 2px solid #9b9b9b;
  color: #9b9b9b;
}
.container .dropdown .dropdown-options li a.active:hover {
  color: #9b9b9b;
}
<div class="container">
  <div class="dropdown">
    <button>Type</button>
    <ul class="dropdown-options">
      <li class="option">
        <a href="#">A</a>
      </li>
      <li class="option">
        <a href="#">B</a>
      </li>
      <li class="option">
        <a href="#">C</a>
      </li>
      <li class="option">
        <a href="#">D</a>
      </li>
    </ul>
  </div>
</div>

In the clickFn method, utilize console.log(e.target.innerText); to capture events.

This approach may assist in retrieving the selected value of the li element.

Answer №2

Within your `clickFn` function, you are already updating the content of the selected button to `btn.innerHTML = this.text;`

The initial text displayed on the button is `Type`. You can validate the button text during form submission by checking:


if (btn.innerText === "Type")
   // User has not selected an option - Show alert
else
   // User has selected an option - Proceed with validating other fields

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

Retrieve Chosen Option in AngularJS

One issue I am facing is related to an ng-repeat that displays users in rows. When a user is clicked, it opens a modal popup for editing the user and displays all user details. However, when I select another role for the user and try to retrieve the newly ...

Enhanced functionality in MUI TablePagination now allows users to easily select their desired page

I've implemented MUI TablePagination to enable pagination in my table. The code is performing well, offering most of the features I need: Users can choose between displaying 5, 10, or 20 entries per page using a dropdown. The number of pages displaye ...

Guidelines for choosing and uploading a file using Ionic

Is there a way to upload a PDF file to a server using the $cordovaFileTransfer plugin? I currently have an input field like this: <input type="file" onchange="angular.element(this).scope().fileNameChanged(this)"> How can I retrieve the pathForFile ...

The Firefox parent was not appearing on the screen

I'm facing an issue with Firefox not displaying my website properly. It seems to be struggling with the styling of a parent div. Have a look at these images. Here is how it's supposed to appear: My website in Chrome/IE http://www.lackeycomputing ...

Adjust the dimensions of the Twitter Bootstrap Modal to match the maximum resolution of the user's screen

When the "Launch demo modal" button is clicked: I would like the modal to adjust its width and height based on the user's screen resolution, maximizing the available space. Additionally, I want the modal to appear in the top left corner of the docume ...

Pass the search query and a specific flag to a PHP function using the Ajax method

I need help figuring out how to filter autocomplete results based on a custom flag being sent to the function along with the search term. This would allow users to specify additional criteria, like finding cities with a stadium or swimming pool. var filt ...

Issue with integrating Bootstrap into Angular 2

When attempting to link to the bootstrap.css file located in the node_modules folder within index.html, I encountered an error. The application's folder structure is as follows: ecommerce-app/node_modules ecommerce-app/src/app/index.html All attem ...

Storing a credit card number securely using Stripe in a MERN stack application

Currently, I am working on an application using the MERN stack where users can create companies. Each company requires various details such as name, address, phone number, email, and credit card information including the 16-digit card number, expiration da ...

Troubleshooting: Navigation bar toggler malfunctioning

Hello, I am facing a problem with the navbar-toggler. Can you please take a look at my code below: <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <link rel="stylesheet" href="css/bootstrap.min.css" ...

The realm of jQuery entities and attributes

let firstElement = document.body.children[0]; $('li', firstElement); // creating a selection within another selection let paragraphSelection = $('p'); $('a', paragraphSelection); This code snippet is taken from a tutorial fo ...

Jasmine: create a mock ajax success callback and provide it with an argument

I'm interested in writing a Jasmine test that verifies the display of a specific string in the browser when a button triggers an AJAX call to retrieve a JSON object from an API. This JSON object then undergoes a function for extracting essential data. ...

What is the method for altering the rendered component?

I'm completely new to React.js and I'm in the process of creating changeable layouts using React.js. I attempted to utilize useState to render specific layouts upon clicking, but encountered an issue when adding setState within a function which r ...

Verifying whether an ng-repeat returns an empty set following a filter operation

I am attempting to achieve the following: Display a list of approximately 50 items using ng-repeat Filter the list based on a text field (ng-repeat="note in notes|filter:basicFilter") If the basic filter returns no results (or a small number, like 5), ma ...

How to Redirect a Webpage to the Same Tab in ASP.NET

I am currently using an asp.net hyperlink control to direct users to a web URL when the hyperlink is clicked. My goal is for the user to open a new tab, rather than a new window, when they click the hyperlink. If the user clicks the link again, I want th ...

Issue detected in AngularJS 1.6 app: Attempting to convert pagination of items into a service results in failure

Currently, I am developing a compact Contact application using Bootstrap 4 along with AngularJS v1.6.6. This application is designed to showcase a JSON file containing various user data. Considering the large dataset in the JSON, the app features a pagina ...

What could be causing the removeChild() method to fail when trying to delete a list item in JavaScript DOM manipulation?

Check out this interactive shopping list. You can add items, delete them, and mark them as completed. Adding and deleting items works fine, but there's an issue when toggling them. Issue (occurs when toggling multiple list items) If you add 3 items ...

What's the best way to eliminate blank space in my Bootstrap grid columns?

I'm facing an issue with the search filter layout on my website. It includes input fields for a search term, two datepickers, and two buttons: <div id="search-holder"> <div id="search-box"> <div ...

Error: The page "..." contains an invalid "default" export. The type "..." is not recognized in Next.js

Currently, I have a functional component set up for the Signup page. My goal is to define props within this component so that I can pass the necessary values to it from another component. This is my current approach: export default function SignupPage({mod ...

What is the best way to use Shadcn to incorporate a calendar that takes up half of my website?

Currently, I am in the process of developing a scheduling appointment system. My main challenge is getting the calendar to take up half of my page's space. Despite my attempts to adjust its height and width, I have not been successful in seeing any ch ...

Is it acceptable to utilize typographical quotation marks within the meta tag of HTML code?

After stumbling upon a website, I noticed that one meta tag stood out: <meta name="”robots”" content="”noindex,nofollow”"> It's worth noting that the attribute values are enclosed in unusual typographical quotation m ...