将选择列表值分配给数组

时间:2013-04-23 07:44:35

标签: javascript html arrays selectlist

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

var listarray = new Array(); 

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

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

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

4 个答案:

答案 0 :(得分: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中的选择框中。

希望它对你有所帮助。

答案 1 :(得分:5)

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

var el = document.getElementsByTagName('select')

在jQuery中你可以这样做。

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

答案 2 :(得分: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/

答案 3 :(得分: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>

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