I am trying to find the value of the optgroup label of currently selected option in a select control. below is some html to show what im trying to do.
<select id='sector_select' name='sector_select' data-placeholder="Select Sector..." style="width:200px;" class="chzn-select">
<option value='' selected='selected'>All Sectors</a>
<optgroup label="Consultancy Services">
<option value='Employment placement/ recruitment'>Employment placement/ recruitment</option>
</optgroup>
<optgroup label="Supplies">
<option value='Food, beverages and related products'>Food, beverages and related products</option>
</optgroup>
</select>
<script type="text/javascript">
$('#sector_select').change(function ()
{
var label=$('sector_select :selected').parent().attr('label');
console.log(label);
});
</script>
the above code gives undefined because its reading parent of select element other than option. any ideas?
You're missing the
#
in the ID selector.You've also got a spurious
</a>
tag inThe style could use some improvement, after that:
This will still log
undefined
for the<option>
which is not in an<optgroup>
; how you handle that scenario is up to you. Demo: http://jsfiddle.net/mattball/fyLJm/