I have the following code – example on jsFiddle
<select>
<optgroup label="Group1">
<option value="11">Option 1</option>
<option value="12">Option 2</option>
</optgroup>
<optgroup label="Group2">
<option value="21">Option 1</option>
<option value="22">Option 2</option>
</optgroup>
</select>
and some jquery code:
$(document).ready(function() {
$("select optgroup").click(function() {
alert("Clicked " + $(this).attr("label"));
});
This seems pretty straight forward. If I add onclick="javascript:alert(...);" that seems to work … except that the click fires no matter what is clicked.
Why doesn’t this work?
Thanks for your help!
EDIT
It seems there is a misunderstanding in what I’m trying to do here so I need to expand the code a bit to give a better idea.
What I’m shooting for is to be able to do the following:
$(document).ready(function() {
$("select optgroup").children().hide();
$("select optgroup").click(function() {
$(this).children().show();
});
As you can see, trapping a click event on the option and then determining the group won’t work because the options will all be hidden. I want the options displayed when you click the Group (optgroup). Having said that, Chrome doesn’t seem to respect a click on the group and IE only returns the group of the selected item (when you click an optgroup) item.
So the short answer on this seems to be that this is not possible. It is not possible to take a normal select with optionGroups and turn it into an accordion styled select list where initially, only the optiongroup items are displayed and clicking an optiongroup item expands its children (the options).
It seems that no browsers truly support clicking a group item in the select list. While there is an onClick event, the event acts more like you’ve clicked the selected item.