Update the text in a personalized dropdown menu when an option is chosen

After spending some time working on a customized dropdown with the use of CSS and Vanilla JavaScript (Plain JS), I encountered an issue while trying to select and update the dropdown text upon clicking an option:

window.onload = () => {
  let [...options] = document.querySelectorAll('#select .opt');
  let select = document.getElementById('select');
  
  select.addEventListener('click', () => {
    options.forEach(opt => {
      opt.classList.toggle('showOpt');
    });
  });
  options.forEach(opt => {
    opt.addEventListener('click', event => {
      let optArr = select.innerText.split('\n');
      optArr[0] = opt.innerText;
      select.innerText = optArr.join('\n');
    });
  });
}
#select {
  border: none;
  width: 100px;
  padding: 5px;
}
.fas {
  float: right;
}
.opt {
  list-style: none;
  display: none;
  margin: 3px;
  padding: 4px;
  border-bottom: 1px solid green;
}
.opt:hover {
  background: white;
}
.showOpt {
  display: block !important;
}
<link href="https://use.fontawesome.com/releases/v5.0.13/css/all.css" rel="stylesheet"/>
<button id='select'>
  Level 1<i class="fas fa-chevron-down"></i><br/>
  <li class='opt' value='1'>Level 1</li>
  <li class='opt' value='2'>Level 2</li>
  <li class='opt' value='3'>Level 3</li>
  <li class='opt' value='4'>Level 4</li>
</button>

Here is a pen of the above code.

If we consider that the user has selected the Level 3 option,
I am now faced with the question - how do I successfully update the dropdown text (initially set as Level 1) using JavaScript / ES6?


Despite my attempts to utilize the element.innerText function of JavaScript, unfortunately, it did not yield the desired outcome!

Answer №1

To make the header text of the dropdown menu change dynamically based on the selected option, you can enclose it in a element with an ID so that it can be easily targeted and updated.

window.onload = () => {
  let [...options] = document.querySelectorAll('#select .opt');
  let select = document.getElementById('select');
  const selectHead = document.querySelector("#selectHeader");

  select.addEventListener('click', () => {
    options.forEach(opt => {
      opt.classList.toggle('showOpt');
    });
  });

  options.forEach(opt => {
    opt.addEventListener('click', event => {
      selectHead.textContent = event.target.textContent;
    });
  });
}
#select {
  border: none;
  width: 100px;
  padding: 5px;
}
.fas {
  float: right;
}
.opt {
  list-style: none;
  display: none;
  margin: 3px;
  padding: 4px;
  border-bottom: 1px solid green;
}
.opt:hover {
  background: white;
}
.showOpt {
  display: block !important;
}
<link href="https://use.fontawesome.com/releases/v5.0.13/css/all.css" rel="stylesheet"/>
<button id='select'>
  <span id='selectHeader'>Level 1</span><i class="fas fa-chevron-down"></i><br/>
  <li class='opt' value='1'>Level 1</li>
  <li class='opt' value='2'>Level 2</li>
  <li class='opt' value='3'>Level 3</li>
  <li class='opt' value='4'>Level 4</li>
</button>

Answer №2

Enhance the appearance of the chosen option and update the content inside the selected class when an option is clicked.

window.onload = () => {
  let [...options] = document.querySelectorAll('#select .opt');
  let select = document.getElementById('select');
  let selectedOption = document.querySelector('.visible');
  
  select.addEventListener('click', () => {
    options.forEach(opt => {
      opt.classList.toggle('showOpt');
    });
  });
  options.forEach(opt => {
    opt.addEventListener('click', event => {
      selectedOption.innerText = opt.innerText;
    });
  });
}
#select {
  border: none;
  width: 100px;
  padding: 5px;
}
.fas {
  float: right;
}
.opt {
  list-style: none;
  display: none;
  margin: 3px;
  padding: 4px;
  border-bottom: 1px solid green;
}
.opt:hover {
  background: white;
}
.showOpt {
  display: block !important;
}

li {
  list-style: none;
}
<link href="https://use.fontawesome.com/releases/v5.0.13/css/all.css" rel="stylesheet"/>
<button id='select'>

    <li class="visible">Preference A<i class="fas fa-chevron-down"></i></li>
    <li class='opt' value='1'>Preference A</li>
    <li class='opt' value='2'>Preference B</li>
    <li class='opt' value='3'>Preference C</li>
    <li class='opt' value='4'>Preference D</li>

</button>

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

The revolutionary Bootstrap 8 grid layout system

I am in need of a system that consists of 8 columns, and I require a Bootstrap class that will allow an HTML element to span across 2 or more of the columns within the grid. The purpose of this is to create a PMS (Property Management System), where certai ...

How to verify if an object is empty in an AngularJS expression

I need to display either a Login or Logout button based on the value of a $rootScope variable. Currently, only the Logout button is showing up in the li tag below. I have specific actions that should occur after certain events: After Logging In:- $root ...

Problematic response design

On my responsive website, I am utilizing the hr tag in various places. However, I have noticed that some lines appear with different thicknesses, as shown in the example below. For a demonstration, you can view a sample on this fiddle: http://fiddle.jshel ...

New Relic identifies mysterious delays caused by MongoDB's findOne method

After setting up newrelic to pinpoint the bottlenecks in my app, I discovered a major issue that has left me stumped. The source of most delays seems to be mongoDB user.findOne, but the biggest challenge is locating where in the code this delay is occurri ...

Generating a file using buffer information in node.js

From the front-end client side, I am sending a file to the server. On the server-side, the data received looks something like this: { name: 'CV-FILIPECOSTA.pdf', data: <Buffer 25 50 44 46 2d 31 2e 35 0d 25 e2 e3 cf d3 0d 0a 31 20 30 20 6f 6 ...

Padding for the doughnut chart in Chart.js canvas

My current setup includes a canvas featuring a doughnut chart created with chart.js enclosed in a div element that displays like this: The canvas has a red background to enhance visibility. Currently, the chart is centered within the canvas with additiona ...

What is the best way to set up jest to generate coverage reports for Selenium tests?

I recently made the switch to using jest for testing my JavaScript project after encountering coverage issues with mocha and chai. While my unit tests are providing coverage data, my Selenium tests are not. I've tried various solutions found in outdat ...

Link to download an Excel spreadsheet

My server is capable of generating excel files dynamically, and I am utilizing AJAX to download these dynamic excel files. Upon successful completion in the callback function, I receive the data for the excel file. $.ajax({ url: exporting. ...

Can we disable hydration warnings for all nested children within a component in NextJS?

Note: I am currently using NextJS 14, but I suspect this issue also exists in NextJS 13. I have created a ThemeToggle component that utilizes the next-themes package. Even if I develop my own version of next-themes using React Context or another state man ...

Find the parent element that houses a particular child element

I am searching for a way to identify all the parent elements that have a certain child element within them. <tr> <i class="myClass"> </i> </tr> For example, I want to find all tr elements that contain an i element with the specif ...

Determine in Node.js whether an image is empty or not

I am in the process of developing a testing application that generates an image based on the URL provided by the user. The screenshots are captured using phantomJS and nightmareJS. Occasionally, users may input a non-existent URL, resulting in a blank ima ...

Unable to display the absolute path of the image src in WebStorm

Hey there! I recently started learning HTML5 and have been using WebStorm on my trusty Macbook Air for about two weeks now. I've encountered a problem with image sourcing that has left me puzzled. Here's my question: Why is it that images from ...

problem with passing the identification number into the function

I am facing an issue with passing the id into a javascript onClick method. I am using the Spring framework and in the controller class, I send the related id to the JSP file like this: model.addAttribute("uploadid", uploadid); Afterwards, I need to p ...

Is styling in React not showing up?

Currently, I am tackling a third-party pagination component in Reactjs. The npm package instructs me to include the line import "rc-pagination/assets/index.css"; in the file. However, despite injecting the index.css into the DOM using the style loader, I ...

The React Testing Library encountered an error: TypeError - actImplementation function not found

Encountering a TypeError: actImplementation is not a function error while testing out this component import React from 'react'; import { StyledHeaderContainer, StyledTitle } from './styled'; export const Header = () => { return ( ...

Use the zoom feature on D3 to enhance two graphs in an HTML document

I have been experimenting with d3 libraries lately and came across http://bl.ocks.org/jroetman/9b4c0599a4996edef0ab. I successfully used it to draw a graph based on data from a tsv file and enable zoom in and out functionality, which worked well for me. Ho ...

Tips for ensuring elements within a modal receive immediate focus when opened in Angular 2

I am relatively new to Angular JS and I am encountering some challenges with implementing a directive in Angular 2 that can manage focusing on the modal when it is opened by clicking a button. There have been similar queries in the past, with solutions pr ...

How can you retrieve the <head> content from a remote website without being able to make any changes to that site?

Imagine I need to access the <head> tag of a remote website like YouTube. Whenever I attempt this, I encounter an error message: Access to XMLHttpRequest at ‘Website I am trying to access for the head section’ from origin ‘My Website’ has b ...

The td data is appearing fragmented and not continuous in one line

Why is the td element on my webpage not appearing on a single line? The weekly report for XYZ is displaying on two lines, but I want it to be on one line. Why is the label content showing up on the next line? Output: Weekly Report for Testing project ...

The jQuery function fails to execute when the script source is included in the head of the document

I'm relatively new to working with scripts and sources, assuming I could easily add them to the header and then include multiple scripts or functions afterwards. Everything seemed to be working fine at first, but now I've encountered a problem th ...