How to get a group of options for a selected item in .chosen (). change ()

For a simple grouping of parameters, let's say:

<optgroup label="fruit"> <option value="1"> apples </option> <option value="2"> pears </option> </optgroup> <optgroup label="veg"> <option value="3"> neeps </option> <option value="4"> tatties </option> </optgroup> 

I can get a capture of the selected option id ... Usage:

  $('#my-chzn').chosen().change( function(evt) { var id = $(this).val(); // ...or var id_ = $(evt.target).val(); } ); 

But is it possible to capture the <optgroup> label for the selected option? those. is there a knob / selector to capture the meaning of β€œfruit” when the selected option is β€œpears”?

Thanks so much for any help anyone can offer ....

+7
source share
1 answer

You can do what you want as the code is shown below

 $('.chosen').chosen().change( function (evt) { var label = $(this.options[this.selectedIndex]).closest('optgroup').prop('label'); alert(label); }); 

Violin demo

+9
source

All Articles