I have an array declared in a script:
var myArray = new Array("1", "2", "3", "4", "5" . . . . . "N");
I have a form which contains a drop down menu:
<form id="myForm"> <select id="selectNumber"> <option>Choose a number</option> </select> </form>
Using Javascript, how will I populate the rest of the drop down menu with the array values? So that the options will be "Choose a number", "1", "2", "3", "4", "5" . . . . . "N"?
To set a JavaScript array as options for a select element, we can use the options. add method and the Option constructor. to add the select drop down. to select the select element with querySelector .
ready(function () { var list1 = document. getElementById('firstList'); list1. options[0] = new Option('--Select--', ''); list1. options[1] = new Option('Snacks', 'Snacks'); list1.
The <select> tab is used with <option> tab to create the simple dropdown list in HTML. After that JavaScript helps to perform operation with this list. Other than this, you can use the container tab <div> to create the dropdown list. Add the dropdown items and links inside it.
You'll need to loop through your array elements, create a new DOM node for each and append it to your object:
var select = document.getElementById("selectNumber"); var options = ["1", "2", "3", "4", "5"]; for(var i = 0; i < options.length; i++) { var opt = options[i]; var el = document.createElement("option"); el.textContent = opt; el.value = opt; select.appendChild(el); }
<select id="selectNumber"> <option>Choose a number</option> </select>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With