How to get the optgroup for a multiselect in jQuery?
Asked Answered
P

3

11

I am using a multiselect with options grouped together.

<select title="Fruits" multiple="multiple" id="fruits" name="fruits[]">
    <option selected="selected" label="All" value="">All</option>
    <optgroup label="" class="fruit">
        <option label="apple" value="1">Apple</option>
        <option label="pear" value="2">Pear</option>
        <option label="orange" value="3">Orange</option>
    </optgroup>
    <optgroup label="" class="berries">
        <option label="strawberry" value="4">Strawberry</option>
        <option label="raspberry" value="5">Raspberry</option>
        <option label="blueberry" value="6">Blueberry</option>
    </optgroup>
</select>

I've tried $(this).find("option:selected").parent().attr("label") which only returns the optgroup of the first selected option, meaning if Strawberry and Pear were both selected, optgroup '.fruit' would be returned on both accounts.

Using jQuery, how do I get the optgroup of each selected option?

Pygmy answered 8/12, 2010 at 12:5 Comment(0)
D
16

Try this

$(this).find("option:selected").each(function(){
    $(this).parent().attr("label");
});
Dufour answered 8/12, 2010 at 12:9 Comment(0)
B
4

This may be a little late, but I just finished working on this issue and this seems to be the most elegant solution I have found:

$("#fruits option").filter(":selected").parent("optgroup").attr("label");

Here is a fiddle modified for this particular example (Using the class attribute rather than the label attribute): http://jsfiddle.net/pNjsj/

Hope that helps someone :)

Barbarbarbara answered 7/2, 2012 at 23:14 Comment(1)
If you're catching an event and doing $(e.target).filter(":selected") for some reason it won't work. In that case, $(e.target).find(":selected") works. In fact, find() works in both cases so I recommend you use that instead of filter().Imes
A
3

Try with .each()

$(this).find("option:selected").each(function(){
    alert($(this).parent().attr("label"));
});
Adorable answered 8/12, 2010 at 12:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.