0

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?

2

1 Answer 1

2

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/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.