Unable to display a dynamic dropdown within a Bootstrap modal

I'm currently delving into JavaScript and seem to be stuck on a rather trivial problem, unsure of what I might be overlooking.

My predicament lies within a Bootstrap modal where I aim to dynamically append currency codes and exhibit them in a dropdown. Surprisingly, the process operates smoothly outside the bootstrap modal, but there seems to be a hiccup when attempting to append options within the modal.

Below is the snippet of JavaScript code causing the snag:

 
var select = document.getElementById("selectCurrencyDefault");
console.log(select);
var currencySelection = ["AED", "AFN", "ALL", "AMD", ... ]; // Currency codes array
            
for(var i = 0; i < currencySelection.length; i++) {
    var opt = currencySelection[i];
    var el = document.createElement("option");
    el.setAttribute("id", "options");
    el.textContent = opt;
    // el.value = opt;
    select.appendChild(el);
}

Here's the HTML code pertinent to the dropdown situated within the modal:


<div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog modal-lg">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">×</button>
          <h4 class="modal-title">Settings</h4>
        </div>
        <div class="modal-body">

<div class="dropdown">
    <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Default Currency:
    </button>
    <div class="dropdown-menu" id="selectCurrencyDefault" aria-labelledby="dropdownMenuButton">
      
    </div>
</div>

</div>
    <div class="modal-footer">
      <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    </div>
</div>
</div>
</div>

It's intriguing how a simple link appended to the modal functions seamlessly, whereas the integration of JavaScript seems to pose a challenge. Even the addition of z-index in CSS did not yield the desired outcome.

Answer №1

It seems that you have added the bootstrap-5 tag to your question, indicating that you are using Bootstrap V5.3 scripts. However, upon inspection, it appears that your HTML code is not compatible with Bootstrap V5 and instead resembles that of V4.

Once you modify your HTML to align with Bootstrap V5 standards, your code should function correctly:

var select = document.getElementById("selectCurrencyDefault");
// console.log(select);
var currencySelection = [...]; // full list of currency codes

for (var i = 0; i < currencySelection.length; i++) {
  var opt = currencySelection[i];
  var el = document.createElement("option");
  el.setAttribute("id", "options");
  el.textContent = opt;
  select.appendChild(el);
}
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b7d5d8d8c3c4c3c5d6c7f782998499879ad6dbc7dfd686">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="54363b3b20272026352414617a677a64793538243c3565">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>

<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#myModal">
  Launch demo modal
</button>

<div class="modal fade" id="myModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Settings</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div class="dropdown">
          <button class="btn btn-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
            Default Currency:
          </button>
          <div class="dropdown-menu" id="selectCurrencyDefault">
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </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

Transitioning Vue components dynamically

I am facing an issue where the Vue transition is not working as expected for my dynamic components. Check out my code snippet below: <template> <div> <component :is="currentView" transition="fade" transition-mode="out-in">< ...

Error connecting Node.js, express, and socket.io application

My app is a simple one that utilizes the socket.io module for node.js. Everything runs smoothly when I start my server with the command node express_server.js. However, when I try to open my page at http://localhost:8080 in the browser, Node.js throws an e ...

Utilizing the variables defined in the create function within the update function of Phaser 3

I'm facing an issue in my game where I can't access a variable that I declared in the create function when trying to use it in the update function. Here is a snippet of what I'm trying to achieve: create() { const map = this.make. ...

Display two elements within a single table column by utilizing an array in Vue.js

I have a requirement to display 2 items from an array in one table TD ( column ). Below is the example mock data provided: agendas: [ [ { tag: 'p', class: 'm-agenda__date', value: & ...

Leaving the "OK" button untouched in the sweet alert dialog

While implementing sweet alert in my project, I encountered an issue where the button text was not changing and the cancel button was missing on some pages. On certain pages, it only displayed OK. You can see a screenshot below for reference. https://i.s ...

How can I substitute a specific portion of a string with values that correspond to items in an object array?

I am currently working on a task that involves extracting values from objects in a string to perform mathematical operations. While I have managed to retrieve the data and match the values enclosed in brackets, I am facing a roadblock in terms of what step ...

Tips for identifying and swapping values/parameters in a URL during redirect

To provide more clarity on my inquiry, I will outline the details below: There are three links: Link A, Link B, and Link C Link A: {c_val} Link B: {id} Link C: In the database, there is a value adgaf7g6adf6gadfg8a86fgs9f6g The main focus here is when ...

The appearance of HTML dropdown select options is unappealing when viewed on iPhones

Looking for a simple alternative to the dropdown menu implementation on iPhones/iOS for a mobile website (not native app). Any suggestions using HTML/CSS/JavaScript? <!DOCTYPE html> <html> <head> <meta name="viewport" content="initi ...

Having difficulty with JSON.Parse - console is showing an error in the DOCTYPE

I'm having trouble writing JSON data to a div using JQuery: var obj = JSON.parse(data); $('#container').html(obj.services.service[0].code); However, I keep receiving a Syntax error related to my DOCTYPE: <!DOCTYPE HTML PUBLIC "-//W3C// ...

Changing route patterns in NextJS

When deploying a new NextJS app, it is important to preserve legacy routes from the old non-NextJS site. The current setup uses /const-string-[long-unique-hash] for an httpd conf redirect: For example: RewriteRule ^const-string-(.*)$ https://google.com?q ...

Can the break statement be used in jQuery or JavaScript?

I created a function that picks a text based on the input string. If there is a match, it sets it as selected. Here is the function: function chooseDropdownText(dropdownId,selectedValue,hfId){ $('#'+dropdownId+' option').ea ...

Navigating the complexities of managing group radio buttons in React JS within a functional component

I'm looking to implement a functionality where only one radio button can be selected at a time within a group. I've searched online for class component code, but I'm in need of a solution using React hooks. Can someone help me with an onChan ...

Display refined outcomes on the search results page

In my app, the main feature is a search box on the homepage. Users can input their search queries and upon submission, they are redirected to a result page displaying the relevant results along with filtering options. The filtering functionality allows use ...

Best practices for remotely monitoring and managing a server in real-time using HTTP

Looking to view server CPU, RAM, and HDD stats along with gathering info from various logs on my client device (a phone with a browser). Implementing ajax polling. Every 5 seconds, setInterval is used on the client to call a PHP file: Scan a folder c ...

Text parsing with jQuery

Hello fellow developers. I am interested in creating a text parser using jQuery. My goal is to develop a function that can take a string as input and convert it accordingly. Imagine we have a div with the following HTML structure: <div class="item"> ...

Examples of using React tables with Material-UI, such as the Material-UI kitchen sink demo, will showcase how to

Can someone help me figure out why the values are not visible in the react table MUI kitchen sink? When I switch to JSON, the header is visible but the data in the table disappears. Both 'data' and 'data1' have the same structure accord ...

Using AngularJS to bind objects with a checkbox

I am dealing with a nested list of objects that can go up to three levels deep. Each object contains another nested object, and this nesting can continue to multiple levels. I am interested in binding these objects directly to checkboxes so that when I che ...

Changing the style.backgroundImage property overrides any image transition effects

I am currently working on creating a button for a player. You can check out the video (here) The button works, but in order to give it a "pressed" effect, I have to change its background-image on click. However, this action seems to override the transitio ...

Unable to successfully import an external HTML file that contains a script tag

I am currently experiencing an issue with my index.html <!doctype html> <html lang="en"> <head> <meta charset="utf-8> <title>MyApp</title> <link rel="import" href="./common.html"> </head> <body> ...

Issue with React Toggle functionality on mobile devices

I have a hamburger toggle that I found in a template, but it doesn't seem to be functioning correctly. How can I activate the on/off toggle feature? When I click the toggle, nothing happens. What am I missing? <div data-testid="header"> ...