2012-04-10 128 views
19

我试图在选择控件中找到当前选定选项的optgroup标签的值。下面是一些HTML来显示我试图做什么。jquery获取选项OPTGROUP的标签

<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> 

上面的代码给出了未定义,因为它的选择元素的读取父项除了选项以外。有任何想法吗?

回答

39

您错过了ID selector中的#

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

你还要虚假</a>标签在

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

样式可以使用一些改进,在那之后:

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

这仍然会记录undefined<option>这不在<optgroup>;你如何处理这种情况取决于你。演示: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); 
});​ 
+0

删除,我得到这个,当我跑的代码,遗漏的类型错误:对象#有没有方法 '托' – 2012-04-10 17:05:03

+1

你使用jQuery <1.6? http://api.jquery.com/prop如果是这样,请改用'.attr()'。 – 2012-04-10 17:06:08

+0

只是想知道如果你可以写一个函数,它采用任何选择元素ID并返回所选项目的optgroup标签。 'this'把我混淆在$()中。一个函数,我可以使用onchange事件外 – 2012-04-10 17:40:11