Reputation: 1687
How can I store the list of option values from a select box into a variable, delimited by comma?
ie:
<!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>
The var would be the following:
var x = "orange,banana,kiwi,mango,pear,strawberry"
Upvotes: 1
Views: 2969
Reputation: 6820
Using getElementsByTagName('option')
and a for
loop are your friends here.
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(', ');
Upvotes: 0
Reputation: 886
try this
<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>
Upvotes: -2
Reputation: 20313
Try:
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(",");
Upvotes: 0
Reputation: 2429
<select>
s have a property called options
. You can iterate it like a regular array. You can then add their values to another, simple array and use join
to make a comma seperated list out of it.
// 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(",");
Upvotes: 1
Reputation: 253396
I'd suggest, at its simplest:
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();
Upvotes: 8