2012-04-10 12 views
19

選択コントロールで現在選択されているオプションのoptgroupラベルの値を検索しようとしています。以下は、何をしようとしているのかを示すhtmlです。selectオプションのOPTGROUPのJquery get label

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

上記のコードは、オプション以外のselect要素の読み取り親であるため、定義されていません。何か案は?

答えて

39

ID selector#がありません。

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

あなたはまた、スタイルはその後、いくつかの改善を使用することができ

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

にスプリアス</a>タグを持っている:

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

これはまだどの<option>ためundefinedを記録します<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

はを削除私は、コードを実行したときに、私は、捕捉されない例外TypeErrorをこれを得た:オブジェクト#は、方法はありません '小道具' –

+1

あなたは<1.6をjQueryのを使用していますか? http://api.jquery.com/propその場合は、代わりに '.attr()'を使用してください。 –

+0

ちょうどあなたが選択要素のIDを取って、選択された項目のoptgroupラベルを返す関数を書くことができるかどうか疑問に思っています。 'this'は$()内で私を混乱させます。機能は私がonchangeイベントの外で使用することができます –

関連する問題