Joe
Joe

Reputation: 442

Get ALL the options of a multi select in jQuery, including those which are not selected

I've seen plenty of code snippets to retrieve the selected options of a multi select in jQuery, but none of the codes I've seen to retrieve ALL the options of a multi select, including those which are not selected, worked!

What I want to do, is to put all the options in a string, separated by commas. I have this code for elements that are selected:

var selectedOptions2 = $('#relationslist option:selected');
            var selectedValues2 = $.map(selectedOptions2 ,function(option) 
            {
                return option.value;
            }).join(',');

How can I adapt it to put in selectedValues all options, including the ones which are not selected?

Thanks in advance.

Upvotes: 0

Views: 123

Answers (3)

Jay Blanchard
Jay Blanchard

Reputation: 34426

You were really close - just remove :selected from your selector -

http://jsfiddle.net/EekQZ/1/

var selectedOptions2 = $('#relationslist option');             
var selectedValues2 = $.map(selectedOptions2 ,function(option) {
    return option.value;
}).join(',');

Upvotes: 0

Anthony Grist
Anthony Grist

Reputation: 38345

This line of code executes a selector that returns all selected options.

var selectedOptions2 = $('#relationslist option:selected');

The key part is the :selected pseudo-selector, since that's what tells jQuery to only bring back the ones which are currently selected. If you want all options, just take that part out.

Upvotes: 1

techfoobar
techfoobar

Reputation: 66693

You should be able to get all options by using the selector $('#relationslist option'); instead of $('#relationslist option:selected');

i.e.

var selectedOptions2 = $('#relationslist option');
...

Upvotes: 1

Related Questions