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>