Search code examples
jqueryselectmultiple-select

:selected returns false for an option of a select element which has multiple attribute set on runtime


Consider the following situation,

I have a select element

<select>
    <option>a</option>
    <option selected="selected">b</option>
    <option selected="selected">c</option>
</select>

Then using jquery I set the multiple attribute

$( 'select' ).attr( 'multiple', true );

Why does the following code returns false?

$( 'select' ).children( 'option' ).eq( 1 ).is( ':selected' )

While this returns true,

$( 'select' ).children( 'option' ).eq( 2 ).is( ':selected' )

But if the select element's multiple attribute was set manually on the HTML code, both of them returns true. (tried on webkit, firefox and IE)

Is it a mistake on my side, or is this the expected behavior?

Thank you


Solution

  • Because the select is rendered without multiple attribute set, only the last selected option is actually selected. You would need to set the selected options after you allow multiple values.

    Both your queries return what you expect. The thing you miss is that your b option is actually not selected. Check what is rendered in browser.

    EDIT: This line fixes the behaviour, add it after your multiple selection activation:

    $('select').html($('select').html());