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>
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.