I crafted this dropdown menu, but for some reason, the selections aren't registering when clicked. Below is the code I used. Any assistance would be greatly appreciated!

Hi there, I need some help with getting my code to run properly. I've created a dropdown box using HTML and CSS, but it seems like there's an issue with the JavaScript portion as the options are not being selected. I've included a code snippet below for reference. If you could take a look and provide me with some guidance, I would greatly appreciate it. Thank you in advance!

const select = document.querySelector(".select");
const optionsContainer = document.querySelector(".dropdown-list");

const optionsList = document.querySelectorAll(".dropdown-list_item");

.select.addEventListener("click", () =>{
   optionsContainer.classList.toggle("active");
})

optionsList.forEach( o =>{
  o.addEventListener("click",() =>{
    select.innerHTML= o.querySelector("label").innerHTML;
    optionsContainer.classList.remove("active");
  });
});
.dropdown{
  width: 20rem;
  position: relative;
  padding-left: 20%;
  color:white;
}

.dropdown:hover  .dropdown-list {
  opacity: 10;
  visibility: visible;
}

.dropdown-select{
  padding: 1.5rem;
  border-radius: 4px;
  background-color: black;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size:  1.6 rem;
  cursor: pointer;
}

.dropdown-list{
  border-radius: 4px;
  background-color: black;
  position: absolute;
  top:110%;
  left: 29%;
  right: 0;
  opacity: 0;
  visibility: hidden;
  transition: opacity 0.2s linear, visibility 0.2s linear;
}

.dropdown-list_item{
  padding: 1rem;
  font-size: 1.4rem;
}
<div id="wrapper">
    <div id="textbox">
      <div id="content">
        <h1 class="form">COMPLAINT TYPE</h1>
</div>
<div class="dropdown">
  <div class="dropdown-select">
    <span class="select">Selected Type</span>
    <i class="fas fa-angle-down"></i>
    </div>
    <div class="dropdown-list">
      <div class="dropdown-list_item">Drainage System Issue</div>
      <div class="dropdown-list_item">Garbage Collection</div>
      <div class="dropdown-list_item">Public Place Cleanliness</div>
      <div class="dropdown-list_item">Sweeping Of Roads</div>
      <div class="dropdown-list_item">Others</div>
    </div>
  </div>

Answer №1

It seems that the leading . before the select.addEventListener(... may have been mistakenly added during a copy/paste action. Additionally, the error was occurring due to the use of

o.querySelector("label").innerHTML
where there is no corresponding label element in the provided HTML code. If you remove that line and simply use select.innerHTML = o.innerHTML;, it should achieve the desired functionality.

const select = document.querySelector(".select");
const optionsContainer = document.querySelector(".dropdown-list");

const optionsList = document.querySelectorAll(".dropdown-list_item");

select.addEventListener("click", () =>{
   optionsContainer.classList.toggle("active");
})

optionsList.forEach( o =>{
  o.addEventListener("click",() =>{
    select.innerHTML= o.innerHTML;
    optionsContainer.classList.remove("active");
  });
});
.dropdown{
  width: 20rem;
  position: relative;
  padding-left: 20%;
  color:white;
}

.dropdown:hover  .dropdown-list {
  opacity: 10;
  visibility: visible;
  cursor:pointer;
}

.dropdown-select{
  padding: 1.5rem;
  border-radius: 4px;
  background-color: black;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size:  1.6 rem;
  cursor: pointer;
}

.dropdown-list{
  border-radius: 4px;
  background-color: black;
  position: absolute;
  top:110%;
  left: 29%;
  right: 0;
  opacity: 0;
  visibility: hidden;
  transition: opacity 0.2s linear, visibility 0.2s linear;
}

.dropdown-list_item{
  padding: 1rem;
  font-size: 1.4rem;
}
<div id="wrapper">
    <div id="textbox">
        <div id="content">
            <h1 class="form">COMPLAINT TYPE</h1>
        </div>

        <div class="dropdown">
            <div class="dropdown-select">
                <span class="select">Selected Type</span>
                <i class="fas fa-angle-down"></i>
            </div>
            <div class="dropdown-list">
                <div class="dropdown-list_item">Drainage System Issue</div>
                <div class="dropdown-list_item">Garbage Collection</div>
                <div class="dropdown-list_item">Public Place Cleanliness</div>
                <div class="dropdown-list_item">Sweeping Of Roads</div>
                <div class="dropdown-list_item">Others</div>
            </div>
        </div>
    </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

Using jQuery to convert JSON data into an array

My JSON data structure is as follows: { "default": [ [ 1325876000000, 0 ], [ 1325876000000, 0 ], [ 1325876000000, 0 ], [ 1325876000000, 0 ] ], "direct": [ [ 13 ...

Repetitive invocation of functions

I am presenting a listing HTML structure as follows <li class="game-box showlist" id="papp_1249" data-tag="Junior KG,Maths"> <div class="game-box-link" data-id="1249" data-active="yes" data-orientation="landscape" data-ajax="fal ...

Issues with v-on:change not triggering method in nuxt.js

Despite my efforts, I can't seem to get this seemingly simple task to work. I came across a question on Stack Overflow that seemed to address the issue - how to fire an event when v-model changes Here is the component that I am working with: <tem ...

Ways to substitute a single parameter within Vue.js router

We are working on a complex multi-level multi-tenant application, where the hostname is used to identify the 'supplier' account and the customer account is included in the URL structure. For example, our routes are structured like this: /:local ...

Modifying the color of Bootstrap icons

When I use PHP code to print this icon into a table, it looks like this: echo '<button Onclick="" style="border: none; background: none; color:green"><a title="Reenviar" data-toggle="tooltip"><i class="material-icons">&#xE0BE;&l ...

In React, the ES6 prototype method map failed to render anything on the screen

Is there an issue with my map method implementation? var App = React.createClass({ getInitialState(){ return { items:[1,2,3] } }, renderItem(){ return( this.state.items.map((item,i))=> <li key={i}> { ...

How can JavaScript Regular Expressions be used for Form Validation?

For my registration form, I am including fields such as userid, name, email, password, confirm password, and affiliation. Using regular expressions in JavaScript, I am validating these fields. I am attempting to display any validation errors within the for ...

Guide on how to forward the response obtained from an Ajax call to a different HTML page

I am working with a mongoose database that stores data containing an individual's first and last name. The user inputs their first name into a field, triggering an ajax request sent to the file named controller.js. This file generates a JSON response ...

Modify the main element of a component

Vue.js requires only a single root element for each component, which is typically wrapped in a div tag. However, this can lead to unexpected issues, such as breaking the layout when using Bootstrap and inserting a div between specific elements like <b-r ...

send parameter when clicking a link rather than using a hashtag

One interesting feature on my website is a menu link with the attribute title=.roc. When this link is clicked, I want to extract this attribute and click on an element with the same attribute on the destination page. Let's consider a scenario where I ...

Having difficulty using JavaScript regex to replace the middle of content?

I am working with a text name[one][1][two][45][text] Through this pattern, I am able to extract the number "45" /(.*?)rows\]\[([0-9]*)(.*)/; Now, my challenge is how can I change the only 45 to a different digit? Using the same pattern and re ...

What is the best method for incorporating separate CSS files for individual HTML templates within a Flask project?

I am embarking on a Flask project and want to keep things organized by having a separate css file for each html file. Most tutorials available online suggest placing all the CSS code in one /static/styles.css file. However, when I try to run the following ...

What is the reason for including parentheses when evaluating JSON data?

What is the purpose of adding ( and ) around the code when using eval? var strJson = eval("(" + $("#status").val().replace(";","") + ")"); Note: The result of $("#status").val() is similar to {"10000048":"1","25000175":"2","25000268":"3"}; ...

NgOnChanges replaces form control value when user inputs text

In my autocomplete form control component: @Component({ selector: 'app-autocomplete', templateUrl: './app-autocomplete.view.html', changeDetection: ChangeDetectionStrategy.OnPush, }) export class AutoCompleteFilterComponent ...

modifying Redux state according to the position in an array

In my food truck app, I have stored customer orders in the redux state as an array of objects. Each order includes a list of items selected by the customer, along with the count, name, and total price for each item. For example: state.order = [ {item: " ...

What is the best way to write an SQL query to safely insert a record into a table with a dynamic name?

I'm working on a function that can insert a record into a table in PostgreSQL. The catch is that the table name needs to be a parameter for the function, and the column names are determined dynamically. To ensure protection against SQL Injection, I am ...

The number of subscribers grows every time $rootscope.$on is used

I currently have an Angular controller that is quite simple: angular.controller('appCtrl', function ($scope, $rootScope) { $rootscope.$on('channel.message', function () { // do something here } }); In addition, I have a ...

Unable to use .ajax within autocomplete function

I've been struggling for days to make the jQuery autocomplete feature work. Currently, I am able to type in the textbox and see exactly what I want, but the issue arises when I click on the desired option - it does not show up in the textbox. I suspec ...

Routing WebSocket connections with Node.js

Currently, I am in the process of developing a chat application for my company which will run on node js with websocket (ws). The app is designed to cater to various departments within the organization, each with its own set of users. My goal is to ensure ...

I encountered a height discrepancy when attempting to style an unordered list to resemble a table

I have created a set of ul lists that appear as a 2-column table, just as I needed. However, an issue arises when the content of any list increases. The problem is that equal height is not being applied, causing the table to look broken. Here is my Fiddle ...