I'd like to detect if the selection option is under the 'interntaional' optgroup. Right now my appraoch is to detect the closest optgroup from the selected item, and get the contents of its label atribute. I could test that sting for the word 'international'. Other approaches are more then welcome.
As you can tell, from this markup its unfortunate that the optgroup doesn't wrap the child options:
<select id="venue">
<optgroup label="New England"></optgroup>
<option value="1"> NH</option>
<option value="2"> ME</option>
<option value="3"> VT</option>
<option value="4"> MA</option>
<option value="4"> CT</option>
<option value="4"> RI</option>
<optgroup label="International"></optgroup>
<option value="100">Canada</option>
<option value="100">Texas</option>
<option value="100">Mexico</option>
</select>
dropdownval = jQuery('select#venue option:selected').parentsUntil(jQuery('optgroup'), '[label*="international"]').attr('label');
<select id="venue">
<optgroup label="New England"></optgroup>
<option value="1"> NH</option>
<option value="2"> ME</option>
<option value="3"> VT</option>
<option value="4"> MA</option>
<option value="4"> CT</option>
<option value="4"> RI</option>
<optgroup label="International"></optgroup>
<option value="100"> Canada</option>
<option value="100"> Texas</option>
<option value="100"> Mexico</option>
<optgroup label=" Europe"></optgroup>
<option value="100"> Bruges</option>
</select>
If your list is dependably ordered (as presented), then you can skip catching the relationship, ie first()
, etc, and follow .prevAll('optgroup')
all the way up. But if the order of your option
s might change, try .nextAll('optgroup')
, or follow @Barmar's logic to traverse in the direction needed:
$("#venue").change(function() {
$("#venue option:selected").each(function() {
if ($(this).prevAll('optgroup').attr('label') == 'International') {
alert('detected');
}
});
});