0

I have a situation similar to this JavaScript - populate drop down list with array, with one exception. I need the keys to populate the values, not the values.

For example, my array is this:

var months = {"":"--None--", "jan":"January", "feb":"February", "mar":"March"};

In the article mentioned the function works great, but I need the value to be different from the content. Here's my altered code:

var monthOptions = document.getElementById("month");
function loadMonths(months){
    monthOptions.innerHTML = '';
            
    for(var i = 0; i < months.length; i++) {
        var opt =  months[i];
        var el = document.createElement("option");
        el.textContent = opt;
        el.value =  months[i].keys();
        monthOptions.appendChild(el);
     }
}   

My HTML:

<select name="month" id="month" required></select>

1 Answers1

0

The el.textContent = opt is the content setting what you searching for. How to iterate over your dictonary months see here and insert the element setting like this:

for (let [key, value] of Object.entries(months)){
    var el = document.createElement("option");
    el.textContent = value;
    el.value =  key;
    monthOptions.appendChild(el);
}
Hemera
  • 55
  • 1
  • 9