2013-03-26 17 views
1

所選元素的數目我有選擇:得到的jQuery

<select> 
    <option>Option1</option> 
    <option selected>Option2</option> 
    <option>Option3</option> 
</select> 

我怎麼能知道所選元素的數量?
我使用:

var shop_val = $("select option").eq(); 

但其返回的對象,我希望元素的數量和每個項目的價值。

+1

您是指選定元素的數量(計數)?或者已選擇的一個元素的索引(位置)? – Thilo 2013-03-26 06:28:09

+0

我的意思是.index(),對不起英文不好 – Saska 2013-03-26 06:46:43

回答

3
$("select option:selected").index()+1 gives the number 
3

你可以做到這一點

var shop_val = $("select option:selected").length(); 

你能做到這樣也

$("select").change(function() { 
    var str = ""; 
    $("select option:selected").each(function() { 
     str += $(this).text() + " "; 
     }); 
    alert(str); 
}) 
2
  1. 附加價值屬性的選項
  2. $('select').val();
1

可以使用:選定的選擇器t o選擇選定的項目,然後拿到。長度,就像這樣:

var sel = $("#mySelect :selected").length; 
1

我建議:

var shop_val = $("select option:selected").index(); 
1

增加價值屬性作爲

<select> 
    <option value=1>Option1</option> 
    <option selected value=2>Option2</option> 
    <option value=3>Option3</option> 
</select> 

和然後用

$('select').val();

+0

+1。或者看看裏面的文字。似乎比依靠職位更安全。 – Thilo 2013-03-26 07:23:14