John Smith
John Smith

Reputation: 1687

Storing the option values of a select box and storing them into a variable (by comma separated values)

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

Answers (5)

Tricky12
Tricky12

Reputation: 6820

Using getElementsByTagName('option') and a for loop are your friends here.

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(', ');

Upvotes: 0

Janak Prajapati
Janak Prajapati

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

Kiran
Kiran

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(",");

DEMO FIDDLE

Upvotes: 0

Butt4cak3
Butt4cak3

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

David Thomas
David Thomas

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();

JS Fiddle demo.

Upvotes: 8

Related Questions