JimC
JimC

Reputation: 99

jQuery set Multi Select OptGroup options

I have a Multi-Select list with OptGroups like so:

<select multiple="multiple" id="idCountry">
    <optgroup label="ASIA">
      <option value="AUSTRALIA">AUSTRALIA</option>
      <option value="CHINA">CHINA</option>
    </optgroup>
    <optgroup label="EUROPE">
      <option value="FRANCE">FRANCE</option>
      <option value="UK">UK</option>
    </optgroup>
</select>

How can I have jQuery select all the destinations in Europe only for the user by Label? How do I unselect all the destinations in an Optgroup by Label as well?

Added for Ejay's amusement. This is what I've tried but it doesn't work and I don't know where to go from here.

$(".chkRegion").click(function () {
    if (this.checked) {
        var optgroup = $('select optgroup[label="' + this.checked + '"]')
        optgroup.attr('selected', true);
    }
});

Upvotes: 0

Views: 2687

Answers (2)

vasilenicusor
vasilenicusor

Reputation: 2073

var element = $('optgroup[label=EUROPE] option');
element.prop('selected', 'selected');

In case you have multiple select with same group label, add id of select in selector

var element = $('#idCountry optgroup[label=EUROPE] option');
element.prop('selected', 'selected');

JSFiddle demo

Upvotes: 1

charlietfl
charlietfl

Reputation: 171669

To set

$('optgroup[label=EUROPE] option').prop('selected',true);

Change label value and boolean accordingly to unselect

DEMO

Upvotes: 1

Related Questions