• Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.

    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

JavaScript dynamically populating html drop down list through javascript


New Coder
Hello -

I am trying to populate a drop down HTML with data, specifically date values, via javascript.

Assume I have the select drop down list in HTML, with id "inceptionDates"

in the javascript, make reference to the HTML drop down list:

const inceptionDatesddl = document.getElementById("inceptionDates");

now the next assumption, a database call is made in the javascript to retrieve the data, stored in the variable inceptionDates below

The data in inceptionDates is simply

id, inceptiondate
id, inceptiondate
id, inceptiondate


Now I loop through the data, and attempt to translate the inceptiondate date value into the drop down list:
for (let key in inceptionDates) {
                    let option = document.createElement("option");
                    option.setAttribute('value', data[key]);

                    let optionText = document.createTextNode(key);


Trouble is, this results in the Id being populated in the drop down, rather than the inceptiondate, as intended.

Is there a way to get the date value populated into the ddl, rather then the id?
<!DOCTYPE html>
<html lang="en">
    <meta charset="utf-8" />
        cursor: pointer;
  <select id="inceptionDates">
    <option value="">choose one</option>
        const inceptionDatesddl = document.getElementById("inceptionDates"),
              data = [
                        ['01', 'date1'],
                        ['02', 'date2'],
                        ['03', 'date3'],
                        ['04', 'date4'],
                        ['05', 'date5']
            /* here we define what is to be the option value or text */
            inceptionDatesddl.insertAdjacentHTML( 'beforeend', data.map( x => `<option value="${x[0]}">${x[1]}</option>`).join('') );
            /* just for test */
            inceptionDatesddl.addEventListener( 'change', function(){ console.log( this.value ? this.value : 'first option' ) } );
Top Bottom