Reputation: 63547
I have a dropdown menu with different option groups. If someone selects an option, how can I check which optgroup it belongs to? For example if 'ferrari' were selected, how would you determine which optgroup it belongs to?
Feel free to use jQuery or raw javascript.
<select name="testSelect">
<optgroup label="fruits">
<option value="apples">Apples</option>
<option value="oranges">Oranges</option>
<option value="pears">Pears</option>
</optgroup>
<optgroup label="cars">
<option value="ford">ford</option>
<option value="toyota">toyota</option>
<option value="ferrari">ferrari</option>
</optgroup>
</select>
Upvotes: 11
Views: 31438
Reputation: 5604
You can do this using jQuery:
$('select').change(function() {
var selected = $(':selected', this);
alert(selected.closest('optgroup').attr('label'));
});
See a live example here: http://jsfiddle.net/jkeyes/zjLCp/1/
Update: Yes you could use parent
http://jsfiddle.net/jkeyes/zjLCp/2/
alert(selected.parent().attr('label'));
Upvotes: 33
Reputation: 147343
Well, in pure js:
this.options[this.selectedIndex].parentNode.label
Not a single function call and less code to boot. :-)
Upvotes: 12