2012-04-10 30 views
19

Tôi đang cố gắng tìm giá trị của nhãn nhóm chọn của tùy chọn hiện được chọn trong điều khiển chọn. dưới đây là một số html để hiển thị những gì im đang cố gắng làm.Jquery nhận nhãn OPTGROUP của tùy chọn chọn

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

mã ở trên không xác định vì phụ huynh đọc của phần tử chọn khác với tùy chọn. bất kỳ ý tưởng?

Trả lời

39

Bạn đang thiếu # trong số ID selector.

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

Bạn cũng đã có một </a> thẻ giả mạo trong

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

Phong cách có thể sử dụng một số cải tiến, sau đó:

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

này sẽ vẫn đăng nhập undefined cho <option> mà không có trong số <optgroup>; cách bạn xử lý kịch bản đó tùy thuộc vào bạn. 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

loại bỏ các, tôi đã nhận điều này khi tôi chạy mã, lỗi chưa gặp: Object # không có phương pháp 'chống đỡ' –

+1

Bạn đang sử dụng jQuery <1.6? http://api.jquery.com/prop Nếu vậy, hãy sử dụng '.attr()' để thay thế. –

+0

chỉ cần tự hỏi nếu bạn có thể viết lên một chức năng mà mất bất cứ điều gì chọn id phần tử và trả về nhãn nhóm optgroup của mục được chọn. 'this' gây nhầm lẫn cho tôi trong $(). một chức năng tôi có thể sử dụng bên ngoài sự kiện onchange –

Các vấn đề liên quan