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:
- Get the Data from JSON into the DOM object (javascript)
- Create/track the parent HTML element which will contain the options. Keep this reference in a variable.
- Iterate into the data array (or objects) accessed from the JSON
- Get the value of the relevant property within each iteration
- Create the HTML element that will be repeatedly used with each data value. In this case the template should be 'value'
- Append this generated code into the parent element that was stored in #2 above.
- 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.
javascripttag, please also include the Javascript code you have tried so far, so we can help you debug or improve it.