Reputation: 485
I need help with this simple thing. I have a multiple selection input box and I want to get the values of the selected parameter using javascript. The problem is, that when I use:
x=document.form.box.value;
The form looks like this:
<form name="form">
<select name="box" multiple>
<option value="a">A</option>
<option value="b">B</option>
</select>
</form>
I always get just the first selected option. I need to get the values of all selected options as a string, ideally separated by commas. If I for example choose A, I get A, if B, I get B, but when I choose A and B, I get A again.
Any ideas?
Upvotes: 0
Views: 55
Reputation: 39777
First give your select box and ID, this will make it accessible via standard calls:
<select name="box" id="box" multiple>
<option value="a">A</option>
<option value="b">B</option>
</select>
Then you can loop thru individual options, appending only selected ones:
var sel = document.getElementById("box")
var sResult = "";
for (var i = 0; i < sel.options.length; i++) {
if (sel.options[i].selected){
sResult += sel.options[i].value + ','
}
}
if (sResult.length > 1) sResult = sResult.substring(0,sResult.length-1);
Working example: http://jsfiddle.net/LGCY6/2/
Upvotes: 2