Html 将选择列表值分配给数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16163732/
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
Assigning select list values to array
提问by NewBee
I have an array initialised in script
我在脚本中初始化了一个数组
var listarray = new Array();
And have a dynamically created select list ---
并有一个动态创建的选择列表---
<select multiple size=6 width=150 style="width:150px" name="ToLB" >
</select>
My question is how to assign all values of select list to the array. Thanks in advance.
我的问题是如何将选择列表的所有值分配给数组。提前致谢。
回答by qwerty
You can do this like :
你可以这样做:
JQuery-
JQuery-
var optionVal = new Array();
$('select option').each(function() {
optionVal.push($(this).val());
});
Javascript-
Javascript-
var x = document.getElementById("mySelect");
var optionVal = new Array();
for (i = 0; i < x.length; i++) {
optionVal.push(x.options[i].text);
}
This stores all the options in your select box in the array optionVal
.
这会将您的选择框中的所有选项存储在数组中optionVal
。
Hope it helps you.
希望对你有帮助。
回答by Dipesh Parmar
You can use getElementsByTagName
to get all the selectbox
as object.
您可以使用getElementsByTagName
来获取所有selectbox
as 对象。
var el = document.getElementsByTagName('select')
And in jQuery you can do it as below.
在 jQuery 中,您可以按如下方式进行。
var arrayOfValues = $("select").map(function() { return this.value; });
回答by Henrik Andersson
Using plain javascript this is something that would work for you. Now, I've assumed that you have at least some options in your select
使用普通的 javascript 这对你有用。现在,我假设您的选择中至少有一些选项
html
html
<select id="selecty" multiple size=6 width=150 style="width:150px" name="ToLB" >
<option value="monkey">Monkey</option>
</select>
javascript
javascript
var listarray = new Array();
//NOTE: Here you used new as a variable name. New is a reserved keyword so you cant use that as a variable name.
var select = document.getElementById('selecty'); // get the select list
for(var i = 0; i < select.options.length; i++){
listarray.push(select.options[i].value);
}
console.log(listarray);
>> ["monkey"]
Fiddle here:
在这里小提琴:
回答by PilgrimViis
<html>
<body>
<!-- Any list (The main thing that it was built before the launch of the functions of the script) -->
<select id = "mySelect" multiple size=6 width=150 style="width:150px" name="ToLB" >
<option value="1111"></option>
<option value="12"> </option>
<option value="123"></option>
</select>
<script>
var valuesList = new Array();
var mySelect = document.getElementById("mySelect");
var currentOption = mySelect.childNodes;
for (var i=1; i<currentOption.length; i = i+2) { // i+2 needed in order to pass text nodes
valuesList[i-1]=currentOption[i].value;
}
</script>
</body>
</html>
The values ??will be stored in your array. I hope I understand you correctly.
值 ?? 将存储在您的数组中。我希望我能正确理解你。