JavaScript - How to create select options from array

Define an array with the values you want to populate in the <select> element.

var fruits = ["Apple", "Banana", "Orange", "Grapes", "Mango"];

Create a <select> element in your HTML markup.

<select id="mySelect"></select>

Iterate through the array and create <option> elements for each value, then append them to the <select> element.

Here's an example:


document.addEventListener("DOMContentLoaded", function () {
	var fruits = ["Apple", "Banana", "Orange", "Grapes", "Mango"];
    var selectElement = document.getElementById("mySelect"); 
    for (var i = 0; i < fruits.length; i++) {
    	var option = document.createElement("option");
        option.value = fruits[i];
        option.text = fruits[i];
        selectElement.appendChild(option);
    }
});

In this example, the JavaScript code runs after the DOM has loaded (DOMContentLoaded event). It iterates through the fruits array and creates an <option> element for each fruit, setting both the value and text properties of the option. The options are then appended to the <select> element.

When you open this in a browser, you should see a dropdown list with options populated from the fruits array.

Comments

Popular posts from this blog

Idea PhpStorm - How to fix bugs with incorrect code Inspections and Autocomplete

CSS Как прикрепить слой (div) к краю

PHP - How to show expected return array elements