Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - populate drop down list with array

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"?

like image 675
user1296265 Avatar asked Mar 27 '12 18:03

user1296265


People also ask

How can I give an array as options to select element?

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 .

How do you populate values in one HTML dropdown list with another using simple JavaScript?

ready(function () { var list1 = document. getElementById('firstList'); list1. options[0] = new Option('--Select--', ''); list1. options[1] = new Option('Snacks', 'Snacks'); list1.

How do you create a drop down list in JavaScript?

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.


1 Answers

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>
like image 137
Alex Turpin Avatar answered Sep 21 '22 02:09

Alex Turpin