2

I am trying to add array elements to dropdownlist using javascript and refered the following links but it did not work:

Code :

var itemArray=new Array();
var ddlItems=document.getElementById("ddlitemslist").value;
itemArray=["a","b","c"];

for(var i=0;i<itemArray.length;i++)
{
    var opt = itemArray[i];
    var el = document.createElement("option");

    el.textContent = opt;
    el.value = opt;

    ddlItems.option.value=el; /*throws error that 'option' is not part of function*/
}
Community
  • 1
  • 1

3 Answers3

5

If you assign an array to variable, you don't have to init it with new Array(), because you will just overwrite it.

By using new Array() you have created a new, empty array. Then you have basically overwrited it with a different array - itemArray = ["a","b","c"]

If you want to push the dynamically created options to the ddlItems element, use appendChild.

Note: In your particular case, if you want to catch the this select from the DOM, use just document.getElementById() without .value, because we are going to reference to its other attributes, not value itself.

var ddlItems = document.getElementById("ddlitemslist"),
    itemArray = ["a", "b", "c"];
    
    for (var i = 0; i < itemArray.length; i++) {
      var opt = itemArray[i];
      var el = document.createElement("option");
      el.textContent = opt;
      el.value = opt;
      ddlItems.appendChild(el);
    }
<select id='ddlitemslist'></select>
kind user
  • 40,029
  • 7
  • 67
  • 77
0

throws error that 'option' is not part of function

The error you get explain it self, you're trying to call .option.value on ddlitemslist value and not on the object.

You should not return the value in the initialisation of ddlItems variable but the object instead, like :

var ddlItems=document.getElementById("ddlitemslist").value;

Should be :

var ddlItems=document.getElementById("ddlitemslist");

NOTE : No need for var itemArray=new Array();.

Hope this helps.

var itemArray=new Array(); //You could remove this line
var ddlItems = document.getElementById("ddlitemslist"),
itemArray = ["a", "b", "c"];

for (var i = 0; i < itemArray.length; i++) {
  var opt = itemArray[i];
  var el = document.createElement("option");

  el.textContent = opt;
  el.value = opt;

  ddlItems.appendChild(el);
}
<select id='ddlitemslist'></select>
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
0

You have to select select element and then while iterating over array create option elements as children of select element.

You need to replace

var ddlItems=document.getElementById("ddlitemslist").value;

with

var ddlItems=document.getElementById("ddlitemslist");
Yogesh
  • 699
  • 1
  • 6
  • 21