2012-04-10 12 views
19

Sto cercando di trovare il valore dell'etichetta optgroup dell'opzione attualmente selezionata in un controllo selezionato. di seguito è un po 'di HTML per mostrare cosa sto cercando di fare.Jquery ottiene l'etichetta OPTGROUP dell'opzione select

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

il codice precedente dà undefined perché la sua lettura padre di selezionare elemento diverso da opzione. qualche idea?

risposta

39

Ti manca lo # nello ID selector.

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

hai anche avuto una falsa </a> tag nel

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

Lo stile potrebbe utilizzare qualche miglioramento, dopo di che:

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

Questo sarà ancora accedere undefined per la <option> che non è in un <optgroup>; come gestisci questo scenario dipende da te. 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); 
});​ 
+0

rimosso il, ho ottenuto questo quando ho fatto funzionare il codice, TypeError Uncaught: Object # non ha un metodo 'puntellare' –

+1

Si sta utilizzando jQuery <1.6? http://api.jquery.com/prop Se è così, usa invece '.attr()'. –

+0

chiedendo semplicemente se è possibile scrivere una funzione che accetta l'id di elemento select e restituisce l'etichetta optgroup dell'elemento selezionato. il 'questo' mi confonde all'interno di $(). una funzione che posso usare al di fuori dell'evento onchange –