How to Create a HTML Select Element from a JavaScript Array Key-Value Pair?

Estimated read time 1 min read

You can create a HTML select element from a JavaScript array of key-value pairs by dynamically adding option elements to the select element. Here’s an example:

<select id="dropdown">
</select>

<script>
  let items = [
    {value: 'item1', text: 'Item 1'},
    {value: 'item2', text: 'Item 2'},
    {value: 'item3', text: 'Item 3'}
  ];

  let dropdown = document.getElementById('dropdown');

  items.forEach(function(item) {
    let option = document.createElement('option');
    option.value = item.value;
    option.text = item.text;
    dropdown.add(option);
  });
</script>

In this example, the forEach method is used to iterate through the items in the array and create a new option element for each item. The value and text properties of each item are set as the value and text properties of the corresponding option element, respectively. Finally, the option element is added to the select element using the add method.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply