views:

92

answers:

3

Hello.

I have a selection box that allows you to select multiple options. I need to access all the selected values with JavaScript - possible a array of values?

Thank you :-)

+2  A: 
var values = [];
$('#my_select option:selected').each(function(i, selected){
    values[i] = $(selected).attr('value');
});
Soufiane Hassou
This is the incorrect answer and it will not work. It will look for `select` elements that are selected instead of their options, and if that were fixed, it would return the text content of the `option` not the value.
Doug Neiner
I was too quick on the trigger aswell. Actually I could only get your answer to work dcneiner.
meep
@meep - My solution is now fixed. @dcneiner's solution is by far the best one here.
karim79
Thanks for your comments, I edited my code :)
Soufiane Hassou
+1  A: 

I would use $.map:

var values = $('#mySelect option:selected').map(function() {
    return this.value; // or $(this).val()
}).get();
karim79
+2  A: 

This is the best way to get an array of the selected values back:

$("#mySelect").val(); // Return an array of the selected options values

This assumes that multiple="mutliple" and size is greater than one on the select element.

Doug Neiner