8

how can I get the values of dropdownlist to an array?

1
  • 1
    Are you using vanilla Javascript or are you using a library like jQuery or Prototype? Commented Jun 16, 2011 at 21:20

3 Answers 3

25
var ddlArray= new Array();
var ddl = document.getElementById('ddl');
for (i = 0; i < ddl.options.length; i++) {
   ddlArray[i] = ddl .options[i].value;
}

http://jsfiddle.net/2vtmP/

Sign up to request clarification or add additional context in comments.

2 Comments

How to do this with JQuery ?
var ddlArray = []; $('#ddl option').each(function(){ddlArray.push(this.value)});
0

In pure Javascript you can iterate over the child nodes and pull out any nodes that have the nodeName option. Quick example:

var select = document.getElementById('whateverIdToYourSelect');

var arr = [];
for (var i = 0, l = select.childNodes.length; i < l; i++) {
    if (select.childNodes[i].nodeName === 'OPTION') arr.push(select.childNodes[i].innerHTML);
}
alert(arr) // [Contents,Of,Each,Option]

Comments

0
var sel = document.getElementById("yourSelectId");
var opts = sel.options;
var array = new Array();
for(i = 0; i < opts.length; i++)
{
    array.push(opts[i].value);
}

Comments

Your Answer

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