Jquery get label of OPTGROUP of select option

为君一笑 提交于 2019-11-29 11:00:40

问题


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?


回答1:


You're missing the # in the ID selector.

$('#sector_select').change(function ()
{
    //           ↓
    var label=$('#sector_select :selected').parent().attr('label');
    console.log(label);
});

You've also got a spurious </a> tag in

<option value='' selected='selected'>All Sectors</a>

The style could use some improvement, after that:

$('#sector_select').on('change', function ()
{
    var label = $(this.options[this.selectedIndex]).closest('optgroup').prop('label');
    console.log(label);
});

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/


just wondering if you can write up a function that takes whatever select element id and returns optgroup label of selected item. the 'this' confuses me within the $(). a function i can use outside the onchange event

function logOptgroupLabel(id)
{
    var elt = $('#'+id)[0];
    var label = $(elt.options[elt.selectedIndex]).closest('optgroup').prop('label');
    console.log(label);
}

$('#sector_select').on('change', function () {
    logOptgroupLabel(this.id);
});​


来源:https://stackoverflow.com/questions/10093048/jquery-get-label-of-optgroup-of-select-option

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!