99

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

asked Mar 27, 2012 at 18:06
1
  • 4
    Please post your attempt and any error message(s) you're getting. Thank you. Commented Mar 27, 2012 at 18:11

14 Answers 14

145

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>

Tomerikoo
19.6k16 gold badges57 silver badges68 bronze badges
answered Mar 27, 2012 at 18:13
Sign up to request clarification or add additional context in comments.

6 Comments

I've got an error textContent & value are not a function and the solution was to cast opt to String like that: el.textContent = String(opt); el.value = String(opt); that's in case of opt isn't String.
@AbdallahOkasha That doesn't make sense. That error would happen if you tried to use el.textContent like this: el.textContent(opt). If you use it like in my exmaple, it doesn't matter if it's a number the browsers will turn it into a string.
Thanks for caring .. actually, I've tried to write el.textContent = arr[i] or el.value = arr[i] and i have got an error said: value, text and textContent are not functions.
@AbdallahOkasha can you reproduce a minimal example of this error on something like jsfiddle.net and share a link?
This's jsfiddle snippet @alex in this example .text function works well without parsing to string, however in my code it gives me an error i am actually using similar array of string (each contains white spaces). jsfiddle.net/okasha/h1jt3yz1/2
|
69

You can also do it with jQuery:

var options = ["1", "2", "3", "4", "5"];
$('#select').empty();
$.each(options, function(i, p) {
 $('#select').append($('<option></option>').val(p).html(p));
});
answered Sep 19, 2015 at 11:25

Comments

19

I used Alex Turpin's solution with small corrections as mentioned below:

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.text = opt;
 el.value = opt;
 select.add(el);
}​

Corrections because with the appendChild() function it loads when the DOM prepares. So It's not working in old (8 or lesser) IE versions. So with the corrections it's working fine.

Some notes on the differences between add() and appendChild().

Tomerikoo
19.6k16 gold badges57 silver badges68 bronze badges
answered Jan 10, 2017 at 17:00

Comments

14

I found this also works...

var select = document.getElementById("selectNumber"); 
var options = ["1", "2", "3", "4", "5"]; 
// Optional: Clear all existing options first:
select.innerHTML = "";
// Populate list with options:
for(var i = 0; i < options.length; i++) {
 var opt = options[i];
 select.innerHTML += "<option value=\"" + opt + "\">" + opt + "</option>";
}
answered Dec 20, 2015 at 2:15

Comments

13

You'll first get the dropdown element from the DOM, then loop through the array, and add each element as a new option in the dropdown like this:

var myArray = new Array("1", "2", "3", "4", "5");
// Get dropdown element from DOM
var dropdown = document.getElementById("selectNumber");
// Loop through the array
for (var i = 0; i < myArray.length; ++i) {
 // Append the element to the end of Array list
 dropdown[dropdown.length] = new Option(myArray[i], myArray[i]);
}
<form id="myForm">
 <select id="selectNumber">
 <option>Choose a number</option>
 </select>
</form>

This assumes that you're not using JQuery, and you only have the basic DOM API to work with.

Tomerikoo
19.6k16 gold badges57 silver badges68 bronze badges
answered Mar 27, 2012 at 18:18

5 Comments

Note, I ran into this problem when I copy-pasted this code: stackoverflow.com/questions/4404526/…
@NielsBrinch - Don't copy-and-paste directly from JSFiddle. :)
I actually copy-pasted from Stackovervflow, not the fiddle - but maybe the stackoverflow author copy-pasted from his own fiddle and the copy-paste got carried over! :)
@NielsBrinch - What was the error? Was it "dropdown is undefined"?
No, it was exactly the one I linked to. "Unexpected token ILLEGAL" in webkit.
8

Something like this should work:

var dropdown = document.getElementById("dropdown1");
if (dropdown) {
 for (var i=0; i < month.length;++i){ 
 addOption(dropdown, month[i], month[i]);
 }
}
addOption = function(selectbox, text, value) {
 var optn = document.createElement("OPTION");
 optn.text = text;
 optn.value = value;
 selectbox.options.add(optn); 
}

You can refer to this article for more details:
http://www.plus2net.com/javascript_tutorial/list-adding.php

answered Mar 27, 2012 at 18:15

Comments

8
["1","2","3","4"].forEach( function(item) { 
 const optionObj = document.createElement("option");
 optionObj.textContent = item;
 document.getElementById("myselect").appendChild(optionObj);
});
answered Mar 27, 2012 at 18:16

Comments

6

Using template literals would be:

const arr = [1,2,3,4]
var options = arr.map(e=>{return `<option value="${e}">${e}</option>`})
document.getElementById("selectNumber").innerHTML = options.join('')
//document.getElementById("selectNumber").insertAdjacentHTML("beforeend", options);
<form id="myForm">
 <select id="selectNumber">
 <option>Choose a number</option>
 </select>
</form>

answered Jul 4, 2022 at 4:38

5 Comments

Beautiful, compact and simple solution.
Or even document.getElementById("selectNumber = arr.map(val => `<option value="${val}">${val}</option>`); - I would reserve the variable e for event
Even better! 👍
This results in commas in between all the option elements because you're implicitly converting the array to a string. It doesn't seem to show the commas to the end user, but still, I would replace the = options in this answer with = options.join('')
@mplungian: another alternative for the last statement is to insert the array to the select like this: document.getElementById("selectNumber").insertAdjacentHTML("beforeend", options);
4

Here is my answer:

var options = ["1", "2", "3", "4", "5"];
for(m = 0 ; m <= options.length-1; m++){
 var opt= document.createElement("OPTION");
 opt.text = options[m];
 opt.value = (m+1);
 if(options[m] == "5"){
 opt.selected = true;}
document.getElementById("selectNum").options.add(opt);}
answered Dec 21, 2020 at 19:16

1 Comment

This is a code only answer. Please add some explanation what your code is doing.
3

If you're working with React and JSX, you can use the map function. Then you don't need to add DOM nodes manually.

const numsarray = [1, 2, 3, 4, 5];

You can map this into your <options> tag (within <select>)

<select>
 {numsarray.map((num) => (
 <option>{numsarray}</option>
 ))}
</select>
answered Jun 3, 2021 at 5:17

Comments

3
var test = document.getElementById("TestOption");
var arr = ["A","B","C","D"]; 
//remove options if necessary
for(var i=test.options.length- 1;i>= 0;i--) {test.remove(i);} 
//add new options
for(i in arr) {test.add(new Option(arr[i],i));}
answered Jul 28, 2021 at 13:55

1 Comment

Thank you, I was looking for a method to remove before append elements.
1

var list =["muez","devomech","solution"]
var option = "";
 for(var i=0; i<list.length; i++){
 option+= '<option value="'+ list[i] +'">' + list[i] + "</option>"
 
 }
 document.getElementById("deviceoption").innerHTML = option;
<select id="deviceoption"></select>

`

answered Nov 6, 2021 at 21:05

Comments

0
<form id="myForm">
<select id="selectNumber">
 <option>Choose a number</option>
 <script>
 var myArray = new Array("1", "2", "3", "4", "5" . . . . . "N");
 for(i=0; i<myArray.length; i++) { 
 document.write('<option value="' + myArray[i] +'">' + myArray[i] + '</option>');
 }
 </script>
</select>
</form>
answered Oct 17, 2013 at 0:36

Comments

0

Simple jQuery solution that is easy to debug:

<form id="myForm">
 <select id="selectNumber">
 <option>Choose a number</option>
 </select>
</form>
<script>
 var myArray = ["1", "2", "3", "4", "5"];
 for (let i = 0; i < myArray.length; i++) {
 $("#selectNumber").append("<option value='" + myArray[i] + "'>" + myArray[i] + "</option>");
 }
</script>
answered Apr 24, 2021 at 18:53

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.