Methods for dynamically populating dropdown lists with JavaScript and Bootstrap

I have collected all 387 regions for the current date and now I want to dynamically populate a bootstrap dropdown with these regions using JavaScript. Below is the basic HTML code for a bootstrap dropdown:

<div class="dropdown">
  <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Dropdown button
  </button>
  <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
    <a class="dropdown-item" href="#">Action</a>
    <a class="dropdown-item" href="#">Another action</a>
    <a class="dropdown-item" href="#">Something else here</a>
  </div>
</div>

Answer №1

Here is a simple way to achieve this. Ensure that the regions are hardcoded to prevent any potential HTML injection vulnerabilities.

const menu = document.querySelector('.dropdown-menu');
const regions = ['Asia', 'Africa'];
regions.forEach(region => {
    menu.innerHTML += `<a class="dropdown-item" href="#">${region}</a>`;
})

Answer №2

Implementing proper DOM management in JavaScript involves creating the Element object through createElement and utilizing appendChild to insert it into the DOM under the parent div.dropdown-menu:

function addItems() {
  var numberOfItems = 5;
  for (var i = 0; i<numberOfItems; i++) {
    var ele = document.createElement("a");
    ele.classList = "dropdown-item";
    ele.href = "#";
    ele.innerText = "" + i;
    document.querySelector(".dropdown-menu").appendChild(ele);
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.15.0/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="dropdown">
  <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Dropdown button
  </button>
  <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
    <a class="dropdown-item" href="#">Action</a>
    <a class="dropdown-item" href="#">Another action</a>
    <a class="dropdown-item" href="#">Something else here</a>
  </div>
  <button class="btn btn-secondary" type="button" onclick="addItems()">Add List Items</button>
</div>

It is important to note that this example may need adjustments to align with the data structure you are working with. Without details on how the data is being obtained, a tailored solution was not feasible for your specific case.

Answer №3

Here is the approach I took:

function addingItems() {
  /*Storing names of items in an array*/
  var regions=['region1','region2','region3','region4','etc'];

  for(var i=0; i<regions.length; i++){

    var listItem = document.createElement("a");
    listItem.setAttribute("class","dropdown-item");
    listItem.href = "#"; 
    var textNode = document.createTextNode(regions[i]); /*Fetching names of the items*/
    listItem.appendChild(textNode);
    document.getElementsByClassName('dropdown-menu')[0].appendChild(listItem);

  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.15.0/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />

<div class="dropdown">

  <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Dropdown button
  </button>
  
  <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
  
    <a class="dropdown-item" href="#">Action</a>
    <a class="dropdown-item" href="#">Another action</a>
    <a class="dropdown-item" href="#">Something else here</a>
    
  </div>
  
  <button class="btn btn-secondary" type="button" onclick="addingItems()">
     Add Items
  </button>
  
</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

How to design a dictionary schema using Mongoose

I have been attempting to save a dictionary of objects using Mongoose. Upon realizing that the change detection for saving is lost when using the Mixed type, I am looking for a way to create a schema that does not rely on the Mixed type. While there are m ...

Exploring Autocomplete Functionality with SQLite Integration in Flask

I have been searching for a solution to my problem without any success. My SQLite database contains electronic products, and I have a search box that allows users to search for products by typing in their name. However, I want to enhance the user experienc ...

Searching for a specific row of data by ID in a massive CSV file using Node.js

Can someone recommend an npm package that is ideal for iterating over a csv file, locating a specific value, and updating/appending to that particular row? I don't have any code to display at the moment as I'm in the process of testing different ...

The function persists in outputting a true result, despite the fact that it is expected to output

Currently, I am working on a NextJS project where I have a client-side form. I've been attempting to implement validation for the form by creating a separate function called validateForm(). However, no matter what input is provided, the function alway ...

I need to find a way to properly test a recursive, async JavaScript function by utilizing fake timers

I've been working with a basic recursive function that performs as expected when run. To thoroughly test its operation at each stage, I want to utilize Sinon's fake timers. Unfortunately, it seems that the fake timers are only affecting the init ...

Error: The function "execute" has not been declared

Hey there! I've created a Discord bot that is meant to check the status of a Minecraft server, but I'm encountering an issue with the embed. It's showing this error: UnhandledPromiseRejectionWarning: ReferenceError: execute is not defined. ...

What is the best way to access and utilize the data stored in my database using mySQL, PHP, and JavaScript?

My Objective : When a user selects a location from the dropdown list, I want the function "newMark()" to place a marker on Google Maps; Current Achievements : The map is displayed along with the select field containing all locations saved in my database. ...

Sort an array using another array as the reference in JavaScript

I have encountered similar questions before, but my current challenge involves partially sorting an array based on values from another array. This is what I aim to achieve: let array = [ { name: "Foo", values: [a, b, c, d] }, { name: " ...

Unexpected Behavior when Passing @Input() Data Between Parent and Child Components in Angular 2 Application

I am currently in the process of abstracting out a tabular-data display to transform it into a child component that can be loaded into different parent components. The main aim behind this transformation is to ensure that the overall application remains "d ...

How can the front design of Material-UI's Card header be customized?

Currently, I am facing an issue with the Material-UI card header as the background color is affecting the readability of the default font. My aim is to use the typography prop h4 for the header, but I am struggling to achieve this. https://i.stack.imgur.c ...

Is there a way to retrieve the request object within loopback operational hooks?

I am currently utilizing loopback 3.x and have created an Access Hook within my code. My goal is to include a condition based on the User Agent. Specifically, I am looking to access Request > Headers > User-Agent. Is it feasible to retrieve this in ...

Tips for automatically populating a form in React with specified values

Here is the code I have written: .... const { userProfile, getUserProfile } = useContext(UserContext); useEffect(() => { getUserProfile(); //eslint-disable-next-line }, []); const [user, setUser] = useState({ ...

Node.js application for changing attributes in an HTML string

Within my node.js backend, there exists an object with a specific property named content, which stores an HTML string. The content within includes an img tag that currently has a src attribute containing a base64 string. I am seeking to modify this src att ...

Excessive content spilling over the div container

Hello everyone I've been trying to set up a div that includes an image, a title, and some text. I want the image to be aligned on the left side, with the title and text following on the right. However, I'm having an issue where the text is overf ...

Display dynamic HTML content within an iframe using jQuery Fancybox

Looking to incorporate dynamic content from the server using ajax into a fancybox (iframe)? Check out this method that allows you to display the entire html page: index.html <html> <head> <link href="css/fancybox/jquery.fancybo ...

What is the best way to customize the background color of a highlighted ToggleButton in react-bootstrap?

Currently, I'm using react-bootstrap and facing a challenge in changing the background color of a chosen <ToggleButton> to blue. For instance: <ButtonToolbar> <ToggleButtonGroup type="radio" name="options" ...

Unable to obtain return value in AngularJS controller or view

I have been working on a geolocation and reverse geocoding application. I have a function that is triggered by a button click to call a function in my controller which then calls my service. While the service is able to retrieve values, I am unable to get ...

What is the best way to activate materialise pop-up menus in a React application?

Looking to enhance my React app by adding a NavBar with dropdown functionality. Here's the code snippet: <ul id="dropdown1" className="dropdown-content"> <li><NavLink to="/create">Create lesson ...

Problem with Labels Overlapping and Blocking Text Fields

My issue is that when I interact with the text field, the label "Type your New Task here" moves up and gets covered by what looks like a white overlay. How can I fix this so that the label stays visible at all times? Prior to engagement: https://i.stack.i ...

What is preventing me from stopping the setInterval using window.clearInterval?

Below is the code I have written using window.setInterval and window.clearInterval. The window.setInterval function works fine, but when I attempt to call window.clearInterval, I encounter an error stating that intervalId is not defined. Is there a way t ...