将选择列表值分配给数组

问题描述 投票:5回答:4

我在脚本中初始化了一个数组

var listarray = new Array(); 

并有一个动态创建的选择列表---

<select multiple size=6 width=150 style="width:150px" name="ToLB" >
</select>

我的问题是如何将选择列表的所有值分配给数组。提前致谢。

javascript html arrays selectlist
4个回答
6
投票

你可以这样做:

JQuery-

var optionVal = new Array();
    $('select option').each(function() {
            optionVal.push($(this).val());
        });

Javascript成为

var x = document.getElementById("mySelect"); 
var optionVal = new Array();
for (i = 0; i < x.length; i++) { 
    optionVal.push(x.options[i].text);
}

这将存储数组optionVal中选择框中的所有选项。

希望它能帮到你。


5
投票

您可以使用getElementsByTagName将所有selectbox作为对象。

var el = document.getElementsByTagName('select')

在jQuery中,您可以执行以下操作。

var arrayOfValues = $("select").map(function() { return this.value; });

3
投票

使用普通的JavaScript这是适合你的东西。现在,我假设您的选择中至少有一些选项

html

<select id="selecty" multiple size=6 width=150 style="width:150px" name="ToLB" >
    <option value="monkey">Monkey</option>
</select>

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"]

小提琴:

http://jsfiddle.net/mQH7P/


2
投票
<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>

值将存储在您的数组中。我希望我能正确理解你。

© www.soinside.com 2019 - 2024. All rights reserved.