tags:

views:

119

answers:

3

I have the following scenario.

I have a combobox where multiple selection is available.

                <select id="a" multiple="multiple">
                    <option value="">aaaa</option>
                    <option value="">bbbb</option>
                    <option value="">cccc</option>
                    <option value="">dddd</option>
                </select>

Now I also have a button

<button type="button" id="display">Display</button>

When a user clicks on this button, it should list all the selected values of the dropdown in an alert box

My JS code looks as follows

  $(document).ready(function() {
                $('#display').click(function(){
                    alert($('#a').val());
                });


        });

Any pointers will be appreciated

+3  A: 

You have to find all the selected options:

jQuery(function($) {
    $('#display').click(function() {
        $('#a > :selected').each(function() {
            alert($(this).text());   // using text() here, because the 
        });                          // options have no value..?
    });
});

The manual, as Pim pointed out, is useful:

The .val() method is primarily used to get the values of form elements. In the case of <select multiple="multiple"> elements, the .val() method returns an array containing each selected option.

So, the above should work, but jQuery already does this behind the scenes for you, so this is much easier:

alert($('#a').val().join(", "));

If it's not working for you, it might be because of the fact that your options don't seem to have a value.

nickf
+2  A: 

The jQuery page documenting the .val() function literally tells you what to do: http://api.jquery.com/val/

Pim Jager
+2  A: 

Have you tried each()?

Kai Sellgren