Enhance your website with a dynamic dropdown feature using Javascript and Bootstrap 5, allowing buttons to respond

Currently, I am experimenting with Javascript to dynamically incorporate elements into a Bootstrap 5 dropdown. To guide me, I referred to the relevant documentation which can be found here (https://getbootstrap.com/docs/5.0/components/dropdowns/#menu-items). While I have managed to successfully add a dynamic list to the dropdown, I am facing an issue where I cannot retrieve the selected value through a function. My attempt at using a global variable only returns the name of the last option added to the list.

I would greatly appreciate it if someone could provide insight on how to handle a Bootstrap 5 dropdown event in order to obtain the label string, id or innerHTML. Any advice is welcome!

The code snippets from my simple Javascript and HTML are as follows:

var def_names_list = ["My Name 1", "My Name 2", "My Name 3"]

function collapse_down() {
        console.log('inside collapse')
        console.log('collapse name is ', collapse_label)
        console.log(this)
        //console.log('id is ', id, 'value is ', value)

}
var collapse_label = ''
if (def_names_list.length > 0) {
    var ul = document.getElementById('collapse_dropdown')
    for (var x=0; x<def_names_list.length; x++) {
        collapse_label = ''
        var li = document.createElement("li")
        var but = document.createElement("button")
        var local_name = def_names_list[x]
        but.type = 'button'
        but.className = "dropdown-item"
        but.innerHTML = def_names_list[x]
        but.id = def_names_list[x]
        but.onclick = function() {
            collapse_label = local_name
            collapse_down()
        }
        li.appendChild(but)
        ul.appendChild(li)

    }
}
!DOCTYPE html>
<html lang="en">
    <head>
      <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="34565b5b40474046554474011a041a04195651405507">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">        
    </head>

    <body>
      <button type="button" id='collapse' class="btn btn-primary btn-sm " data-bs-toggle="dropdown" aria-expanded="false"  >Collapse Groups</button>            
      <ul class="dropdown-menu" id="collapse_dropdown" aria-labelledby="collapse"></ul>
      
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2b4944445f585f594a5b6b1e051b051b06494e5f4a18">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"></script>        
    </body>
</html>

Answer №1

It seems like the issue in your code arises from setting the value of collapse_label within the loop. Since the var is global, the value gets overwritten in each iteration of the loop, resulting in only the last name being displayed for any name clicked on.

Here's how you can resolve this:

var default_names_list = ["My Name 1", "My Name 2", "My Name 3"];

function collapse_down(elem) {
  // console.log("inside collapse");
  console.log(elem);
  console.log("Value: " + elem.value);
  console.log("ID: " + elem.id);
  console.log("InnerHTML: " + elem.innerHTML);
}
if (default_names_list.length > 0) {
  var ul = document.getElementById("collapse_dropdown");
  for (var name of default_names_list) {
    var li = document.createElement("li");
    var button = document.createElement("button");
    button.className = "dropdown-item";
    button.innerHTML = name;
    button.value = name;
    button.id = name;
    button.onclick = function() {
      collapse_down(this);
    };
    li.appendChild(button);
    ul.appendChild(li);
  }
}
<!DOCTYPE html>
<html lang="en">
<head>
  <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bdcfcacab6c8cabecadd9cecefbaebbcad81dededfdb">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous" />
</head>

<body>
  <button type="button" id="collapse" class="btn btn-primary btn-sm" data-bs-toggle="dropdown" aria-expanded="false">
    Collapse Group
  </button>
  <ul class="dropdown-menu" id="collapse_dropdown" aria-labelledby="collapse"></ul>

  <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="43313d3d233e382a09112e25122b1306372c223b372590232e282a302725332833273775">[email protected]</a>/dist/js/bootstrap.bundle.min.js"
    integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf"
    crossorigin="anonymous"></script>
  <script src="./src/index.js"></script>
</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

Learn how to showcase the value of the selected radio button in AngularJS

To show the chosen radio button in the response div, make sure to hide the div if no option is selected. Check out the code below: <body ng-app="QuestionDisplayModule"> <form> <div ng-controller="QuestionDisplayController" ...

The type '{ }' does not include the properties 'params', 'isExact', 'path', 'url' from the 'match<Identifiable>' type

Currently, I am utilizing react router and typescript in order to extract the id variable from a route for use in a component. However, typescript is raising an issue: The type '{}' lacks the following properties found in type 'match' ...

invoking a JavaScript function from an HTML file

I want to create a JavaScript server on Raspbian that not only serves .html content to the browser but also allows for user input through events like button clicks. Both my .html and .js files are located in the same directory, and I have used absolute pat ...

Unusual trait of TrackballControls.target within the world of Three.js

My current project involves simulating a 3D distribution of galaxies. In this simulation, the galaxies are represented as points. question1.htm references galaxydata1.txt to calculate and load the galaxy positions: rawFile.open("GET", "galaxydata1.txt", ...

Transferring an object from the factory to the controller

I'm currently working on setting up a factory that sends an ajax request to an API and then returns a data object. Here is the code snippet I have written: app.factory('Test', function($http, $q) { var data = {response:{}}; var getM ...

Example of Node-gallery used in isolation, displaying an error event with the message "ENOENT"

I am currently experiencing an issue with the node-gallery npm module. After installing dependencies inside the /example directory, I attempted to run the app. The result was a localhost:3000/gallery page, but upon the page fully loading, I encountered the ...

Even when the outcome is not what was anticipated, mocha chai still manages to ace the examination

When testing my REST API response with mocha, chai, and express, I set the expected status to 201 but unexpectedly got a passing test result it('janus post', () => { request('https://***') .post('/***') .attach(&a ...

Choosing comparable choices from the drop-down menu

I am working on a dropdown menu that contains different options. I need to use jQuery to automatically select the option that corresponds to the branch of the currently logged in user. However, when some option text is very similar, it causes an issue. // ...

When working with Vuejs Composition API, I noticed that the value of a Reference object seems to disappear when I

Here is the code snippet that I am working with: <template> {{posts}} </template> <script> import { computed, ref } from 'vue'; import getPosts from '../composables/getPosts.js' import {useRoute} from 'vue-router ...

What is the proper way to select the <ul> element within an FTL template?

Can someone provide guidance on how to target a <ul> container within a freemarker template using JavaScript? My goal is to display the content of this specific <ul> element in my FreeMarker template on the web page. Any suggestions on how I ...

Tips for initiating a component within a loop and terminating it after completing all 3 iterations

Looking for a solution to open and close tags in a loop every 3 iterations. The objective is to create a grid using container, row, and column elements. However, I am unsure how to achieve this. Example: render(){ const arrayName = ["john", " ...

Encountering an issue while trying to set up Gulp js on my

I'm facing an issue while trying to set up Gulp js on my system. It seems like the installation is incomplete as running gulp -v in powershell gives the following output: [12:43:04] CLI version 1.3.0 [12:43:04] Local version 3.9.1 However, when att ...

React-virtualized list experiencing performance problems due to react-tether integration within its elements

Description I need help with a challenging issue. I have a long list of items displayed in a react-virtualized VirtualScroll. Each item on the list contains many elements, including one that triggers a context menu. I'm using react-tether to attach t ...

What is the best way to change an existing boolean value in Prisma using MongoDB?

Exploring prisma with mongoDb for the first time and faced a challenge. I need to update a boolean value in a collection but struggling to find the right query to switch it between true and false... :( const updateUser = await prisma.user.update({ where: ...

What are the best methods for customizing the backgrounds of the form-floating input labels in the latest version of Bootstrap?

I'm currently using Bootstrap 5.3 and experimenting with the new "floating labels" feature. I want to add some extra styling to my input fields, like background colors. However, when I initially set a subtle green background color, it looks fine witho ...

Is there a way to trim JSONP data to only obtain the year value

My current setup involves using an API to fetch data, which includes the release date of a game. '<h4 style="display:inline-block; padding-left:5px;" class="post-title">' + game.name + ' <span class="small">' + game.origin ...

Creating a C# view model with jQuery integration

I am facing an issue with binding a list property of a view model using jQuery. The view model in question is as follows: public class ToolsAddViewModel { public string Tools_Name { get; set; } public string Tools_Desc { get; set; } ...

What is the most efficient method to import multiple MaterialUI components using a shared namespace without requiring the entire library to be imported

In order to prevent name mixing with other libraries, I want my MaterialUI components to be under the same namespace. For example, ensuring that <Box> references <MaterialUI.Box> and not <SomeOtherLibrary.Box>. Although it seems like a si ...

Encountering an issue with finding the module `scheduler/tracing` in React Native

Encountering an error during the react-native run-android process: Error: Unable to resolve module `scheduler/tracing` from `/Users/miftahali/projects/react/appscustomec/node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js`: Module ...

JavaScript form button press tracker

Hello! I've been tackling a challenge involving a JavaScript function to count button clicks. The catch is, the button type is set to submit, causing the page to reload every time I click it. Below is the snippet of code that contains the problemati ...