Using ES6 without the need for jQuery, populate a select element with JSON data using Javascript

I have a json-formatted dataset that I want to incorporate into my select options.

Here is the data:

 {
    "timezones": 
    {
        "country": "Africa",
        "tz": "Africa/Abidjan"
    },
    {
        "country": "America",
        "tz": "America/Anguilla"
    }
}

Below is the current select menu:

<select>

    <optgroup label="Africa">
        <option value="Africa/Abidjan">Adak</option>
    </optgroup>

    <optgroup label="America">
        <option value="America/Adak">Anguilla</option>
    </optgroup>

</select>

Is there a way to dynamically populate the select menu with the json data provided, without using jQuery?

Answer №1

One way to achieve this is by using the `appendChild` method along with the `.forEach` method.

let data = {
    "timezones": 
    [{
        "country": "Africa",
        "tz": "Africa/Abidjan"
    },
    {
        "country": "America",
        "tz": "America/Anguilla"
    }]
};
let select = document.getElementById('countrySelect');
data.timezones.forEach(function(item){
  let newOptGroup= document.createElement('optgroup');
  newOptGroup.label=item.country;
  let option=document.createElement('option');
  option.value=item.tz;
  option.text=item.tz;
  newOptGroup.appendChild(option);
  select.appendChild(newOptGroup);
});
<select id="countrySelect">

</select>

Answer №2

In the beginning, your JSON data is considered invalid. The 'timezones' attribute should either be an array or have an index on every object.

Below is the provided data:

let data = {
  "timezones": [
  {
      "country": "Africa",
      "tz": "Africa/Abidjan"
  },
  {
      "country": "America",
      "tz": "America/Anguilla"
  }]
}

Here's how I would populate the options:

data.timeszones.forEach(function(timezone) {
  let optionGroup = document.createElement('optgroup');
      optionGroup.setAttribute('label', timezone.country);

  let option = document.createElement('option');
      option.setAttribute('value', timezone.tz);

  optionGroup.appendChild(option);
  document.getElementById('selectionList').appendChild(optionGroup);
});

Lastly, ensure to assign an ID to your <select> element.

<select id='selectionList'>
    <optgroup label="Africa">
        <option value="Africa/Abidjan">Adak</option>
    </optgroup>

    <optgroup label="America">
        <option value="America/Adak">Anguilla</option>
    </optgroup> 
</select>

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

Guidelines for utilizing recursion in order to calculate the sum of specified values within a multidimensional array

I am dealing with a complex object data that resembles the structure provided below. My objective is to calculate the total direct package values for the top users, or "parents" compute the combined nested indirect package values from the subtree of "ch ...

Finding the identifier for resources through excluding external influences

I am currently facing an issue with the full calendar plugin. In my set up, I have 3 resources along with some external events. The problem arises when I try to drop an external event onto the calendar - I want to retrieve the resource id from which the ev ...

Utilizing Firebase messaging onMessage function is exclusively enabled within a window environment

Incorporating Firebase Cloud Messaging into my project allowed me to send and receive push notifications successfully. While I can receive the push notifications, unfortunately, I am encountering issues with getting the notification events to function prop ...

jasmine and protractor test failing due to use of byID

My HTML markup is all set and valid. While using WebStorm to debug my test cases, I am able to view this specific element without any issues... <a id="privacyPolicy1234" on-tap="goPrivacyPolicy()" class="disable-user-behavior">Privacy Policy</a&g ...

Firefox causing issues with Rails Ajax functionality

My Rails application includes an AJAX call that currently triggers a JavaScript alert message. While this functionality works smoothly on Safari and Chrome, it strangely fails to function on Firefox (across all its recent versions). I tried debugging the c ...

Determine the specific button that was clicked within a React component

I have a challenge with dynamically generated material UI buttons. I am trying to identify which button was clicked by obtaining the value of the name attribute that I assigned to each button. Is there a way to accomplish this? In essence, I need to retrie ...

The debate between using backticks and colons in TypeORM queries

Lately, I've been crafting queries utilizing backticks const firstUser = await connection .getRepository(User) .createQueryBuilder("user") .where(`user.id = '${id}'`) .getOne(); However, in the typeorm documentatio ...

Obtaining a fresh access token from a refresh token using the googleapis npm library

I've been searching everywhere for an explanation, but I can't seem to find one. The documentation I've read says that refresh tokens are used to obtain new access tokens, but it doesn't explain the mechanics behind it. Normally, I wou ...

Issues with jQuery code functionality within web forms

After creating a jQuery script to alter the CSS of a table row, I tested it on JSFiddle and it worked perfectly. However, when implemented into my web project, it doesn't seem to be functioning as intended. See the code below: HTML: <script src ...

Guide to utilizing a JWT token within an httpOnly cookie for accessing a secured API endpoint

Utilizing next.js and next-auth for user login authentication with an API. Once the login is successful, a httpOnly cookie named __Secure-next-auth.session-token is stored in the browser. The following is a sample value (not actual data): eyJhbGciOiJIUzUxM ...

How to dynamically disable options in a Vuetify v-select based on the type of object value

When utilizing the Vuetify v-select component and setting the prop multiple, we can select multiple values at once. In this scenario, I have a variety of recipes categorized under Breakfast or Dinner using the parameter type. The goal is to deactivate al ...

Transferring information from the router to the server file using Node.js and Express

I am in the process of creating a web application using node.js, and I need to transfer data from my router file, which handles form processing, to my server file responsible for emitting events to other connected users. router.js module.exports=function ...

The returned type of intersected functions in Typescript does not match the inferred type

While attempting to extract the return type of an intersected request, I encountered a discrepancy between the return type and the inferred type. Check out the shortened URL for more details: https://tsplay.dev/mAxZZN export {} type Foo = (() => Promis ...

Angular movie database using an API from an apiary

I'm struggling to create a link on movie posters that will lead to detailed movie information based on the movie ID. I have been going through their documentation, but I can't seem to get the api configuration to function properly. Every time I t ...

Utilize JavaScript and jQuery to extract the selected text's context from a webpage

I'm looking to extract the contextual information surrounding a selected text on a web page, specifically the 25 words before and after it. I've tried using JavaScript and jQuery with the following code snippet but unfortunately, it doesn't ...

Display the outcomes of two MongoDB queries simultaneously on a single page

As I dive into the world of MongoDB and Node.js/Express, I find myself struggling to fully grasp some of the concepts. Forgive my inexperience, but I haven't been able to locate a clear answer for what I'm trying to achieve. My goal is straight ...

Navigating with nodeJS

Currently, I am in the process of learning how to create a Node.js project. My latest endeavor involved following a tutorial to develop a chat application. However, it seems like there is an issue with the routing between the server side and client side. ...

trigger a function when the iframe is altered

I am currently working on creating a function that can process credit card payments using an iframe. The challenge I am facing at the moment is dealing with error messages appearing in a less than ideal manner. Photo: I have been attempting to capture the ...

What is the most effective way to display a card with varying values depending on the user's input in a form?

For a while now, I've been grappling with a particular challenge. In my project, I am utilizing multiple states to display values within a card after they are entered into a form. The first state captures the values and modifies the initial state, whi ...

Looking to conceal a JavaScript file or minimize it from the web browser following production build in React

Upon executing the npm run build command using the script provided in my React App's package.json file, "scripts": { "start": "react-scripts start", "build": "set 'GENERATE_SOURCEMAP=false&apos ...