Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
72
rated 0 times [  77] [ 5]  / answers: 1 / hits: 31049  / 12 Years ago, tue, october 23, 2012, 12:00:00

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>

More From » html

 Answers
7

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'));

[#82384] Monday, October 22, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
stefanicarolinat

Total Points: 145
Total Questions: 91
Total Answers: 93

Location: Cambodia
Member since Thu, Oct 7, 2021
3 Years ago
stefanicarolinat questions
Mon, Nov 15, 21, 00:00, 3 Years ago
Fri, Apr 16, 21, 00:00, 3 Years ago
Thu, Oct 15, 20, 00:00, 4 Years ago
Fri, Jul 17, 20, 00:00, 4 Years ago
;