wiggo
wiggo

Reputation: 1

Populate drop-down list in HTML using JSON data

I'm a student and very new to code. I've created a drop-down list using HTML and CSS, and I'm trying to populate it using data from JSON. This is my HTML code:

    <div class="dropdown">
  <button class="dropbtn">Choose your area</button>
  <div class="dropdown-content">
    <a href="#">Place 1</a>
    <a href="#">Place 2</a>
    <a href="#">Place 3</a>

  </div>
</div>

I'm trying to replace 'Place 1', 'Place 2' etc with about 150 real place names. These are in JSON:

    "areaNames": [
 {
   "A": 1,
   "B": "Barking & Dagenham"
 },
 {
   "A": 2,
   "B": "Barnet"
 },

and so on. How do I pull in the place names from JSON to be in the place of 'Place 1', 'Place 2' etc? I've tried following the advice in response to similar tutorials but that seems to give me a list of several separate drop-down boxes rather than a simple list of places.

Thanks for your help.

Upvotes: 0

Views: 3133

Answers (3)

GeeDee
GeeDee

Reputation: 11

I believe you have already loaded the JSON data in the DOM so you can access the data in your javascript. Are you using any javascript library or framework like - jQuery, AngularJS or plain Javascript? It is always better to organize your javascript code externally in a file with extension .js and load it in your HTML using <script> tag within <head> or <body> section.

Steps to generate the anchor tags dynamically in an HTML:

  1. Get the Data from JSON into the DOM object (javascript)
  2. Create/track the parent HTML element which will contain the options. Keep this reference in a variable.
  3. Iterate into the data array (or objects) accessed from the JSON
  4. Get the value of the relevant property within each iteration
  5. Create the HTML element that will be repeatedly used with each data value. In this case the template should be 'value'
  6. Append this generated code into the parent element that was stored in #2 above.
  7. After the iteration is complete, inject (append) the parent element into the DOM at the appropriate place.

Case 1: Plain javascript -

Use XHR to read the JSON and get the data into a variable. Lets name it JSONData.

We will keep the reference of the parent element created in the HTML within javascript.

//hoping that you have only one element with this classname or the

//concerned element is the first element by this classname in this HTML code.

//Generally, as a good practice we should either use ID to identify an element individually within our javascript code,

//else use specific identifiers for the same.

var parentDropdownContainer = document.getElementsByClassName('dropdown-content')[0];

Iterating in the JSON data

for (var counter = 0, len = JSONData.length - 1; counter < len; counter ++){
  //we will add logic to generate HTML
}

You can use the other variants of the iteration - for in, while, Array.splice(), etc upto your understanding.

Within this iterator we need to create a HTML code and append it to the parent container

for (var counter = 0, len = JSONData.length - 1; counter < len; counter ++){
  var currentData = JSONData[counter]; //this holds the reference of the current data in this iteration
  var dropdownElement = document.createElement('a');
  dropdownElement.setAttribute('href','#'); //this adds the href attribute into the anchor element.
  //lets add another attribute to the anchor element to represent the dynamic id/value associated with this data
  dropdownElement.setAttribute('data-value',currentData.A);
  //lets add the value inside the anchor element
  dropdownElement.innerHTML = currentData.B;
  //lets append this element to the parent container
  parentDropdownContainer.appendChild(dropdownElement);
}

Now this should render the required dynamic options in the dropdown.

Upvotes: 0

loelsonk
loelsonk

Reputation: 3598

Here is working example with pure JS.

var areaNames = [
  {
     "A": 1,
     "B": "Barking & Dagenham",
     "C": "https://google.com"
  },
  {
     "A": 2,
     "B": "Barnet",
     "C": "https://google.com"
  }
]

var dropdownContent = document.querySelector('.dropdown-content');

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

  var element = areaNames[i];

  var htmlToAppend = document.createElement('a');
  htmlToAppend.innerHTML = element.B;
  htmlToAppend.href = element.C;
  
  dropdownContent.appendChild(htmlToAppend);
}
a {
  display: block;
}
<div class="dropdown">
  <button class="dropbtn">Choose your area</button>
  <div class="dropdown-content">

  </div>
</div>

Upvotes: 1

jjj
jjj

Reputation: 1154

I don't see a dropdown in the code.

You could use jQuery, which is a Javascript library, to accomplish your goal.

HTML:

<select id="sel">

</select>

JavaScript:

$(function() {
    var data = [
        {
        "id": "1",
        "name": "test1"},
    {
        "id": "2",
        "name": "test2"}
    ];
    $.each(data, function(i, option) {
        $('#sel').append($('<option/>').attr("value", option.id).text(option.name));
    });
})

Upvotes: 0

Related Questions