user1296265
user1296265

Reputation: 999

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

Upvotes: 97

Views: 402333

Answers (14)

jleviaguirre
jleviaguirre

Reputation: 706

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>

Upvotes: 5

DashK
DashK

Reputation: 2670

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.

Upvotes: 13

0190198
0190198

Reputation: 1717

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().

Upvotes: 19

Alex Turpin
Alex Turpin

Reputation: 47776

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>

Upvotes: 145

Muezur rehman
Muezur rehman

Reputation: 11

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>

`

Upvotes: 1

InformediaDev
InformediaDev

Reputation: 31

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));}

Upvotes: 3

vaba-huo
vaba-huo

Reputation: 51

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>

Upvotes: 3

Zaffer
Zaffer

Reputation: 1809

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>

Upvotes: 0

Abdelghafour Lahrache
Abdelghafour Lahrache

Reputation: 41

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);}

Upvotes: 4

Peter Aron Zentai
Peter Aron Zentai

Reputation: 11740

["1","2","3","4"].forEach( function(item) { 
   const optionObj = document.createElement("option");
   optionObj.textContent = item;
   document.getElementById("myselect").appendChild(optionObj);
});

Upvotes: 8

Tim D
Tim D

Reputation: 690

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>";
}

Upvotes: 14

Jaco B
Jaco B

Reputation: 1043

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));
});

Upvotes: 69

vladschwartz
vladschwartz

Reputation: 11

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

Upvotes: 0

James Johnson
James Johnson

Reputation: 46047

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

Upvotes: 8

Related Questions