Get all the values of a dropdownlist to an array u

2019-02-21 19:20发布

问题:

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

回答1:

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/



回答2:

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]


回答3:

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