存储选择框的选项值并将它们存储到变量中(以逗号分隔的值)

时间:2013-09-19 14:05:49

标签: javascript

如何将选项框中的选项值列表存储到以逗号分隔的变量中?

即:

<!DOCTYPE html>

<html>

<head>
    <meta charset="utf-8">

</head>

<body>
<select id="fruits">
  <option value="orange">orange</option>
  <option value="banana">banana</option>
  <option value="kiwi">kiwi</option>
  <option value="mango">mango</option>
  <option value="pear">pear</option>
  <option value="strawberry">strawberry</option>
</select> 
</body>

</html>

var将如下:

var x = "orange,banana,kiwi,mango,pear,strawberry"

5 个答案:

答案 0 :(得分:8)

我建议,最简单的说法是:

var select = document.getElementById('fruits'),
    opts = select.getElementsByTagName('option'),
    x = [];

for (var i = 0, len = opts.length; i < len; i++) {
    x.push(opts[i].value);
}

x = x.join();

JS Fiddle demo

答案 1 :(得分:1)

<select>有一个名为options的属性。您可以像常规数组一样迭代它。然后,您可以将其值添加到另一个简单数组中,并使用join从中创建逗号分隔列表。

// Get the select
var select = document.getElementById("fruits");

// This array will hold the values only
var values = [];

// Iterate the options
for (var i = 0; i < select.options.length; i++) {
  // Store the value inside our array
  values.push(select.options[i].value;
}

// Make a comma seperated list
var x = values.join(",");

答案 2 :(得分:0)

尝试:

var x = document.getElementById('fruits').options;
var values = [];
for(var i=0;i<x.length;i++){
    values.push(x[i].value);
}
var val = values.join(",");

DEMO FIDDLE

答案 3 :(得分:0)

使用getElementsByTagName('option')for循环是您的朋友。

JSFIddle Demo

var options = document.getElementsByTagName('option');
var x = new Array();

for(var i = 0; i < options.length; i++) {
    x.push(options[i].value);
}
x = x.join(', ');

答案 4 :(得分:-2)

试试这个

<select>
<script language="text/javascript">
var x = new Array("orange,banana,kiwi,mango,pear,strawberry");

for(var i=0; i<x.length; i++)
{
document.write("<option value=\""+states[i]+"\">"+states[i]+"</option>");
}
</script>
</select>