Javascript 使用Javascript将下拉列表的所有值获取到数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6378680/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:29:42  来源:igfitidea点击:

Get all the values of a dropdownlist to an array using Javascript

javascriptdrop-down-menu

提问by Dustin Laine

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

如何将下拉列表的值获取到数组?

回答by Dustin Laine

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/

http://jsfiddle.net/2vtmP/

回答by Robert

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

在纯 Javascript 中,您可以遍历子节点并拉出具有 nodeName 选项的任何节点。快速示例:

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]

回答by Arturo Martinez

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