计算jQuery中选择标签中的选项标签的数量


159

如何使用jQuery计算DOM元素中的<option>s 数量<select>

<select data-attr="dropdown" id="input1">
  <option value="Male" id="Male">Male</option>
  <option value="Female" id="Female">Female</option>
</select>

我想<option><select>DOM元素中找到标记的数量,因为要打开带有相应数量的输入字段的设置面板,并从下拉框中选择相应的选项值,然后在预览中再次进行更改面板。

上面的下拉框在我的预览面板中,该面板由jQuery生成。

Answers:



51

W3C解决方案:

var len = document.getElementById("input1").length;

5
这种方法与现代javascript的不同形式将是 var len = document.querySelector("#input1").length;
Jacob Nelson

22

您可以使用length属性中的任何一个,并且length性能更好size

$('#input1 option').length;

或者您可以使用尺寸功能

$('#input1 option').size(); 

演示版


2
这没有提供任何答案,也没有提供2009年的答案。
TylerH

18

您的问题有点令人困惑,但是假设您要在面板中显示选项数量:

<div id="preview"></div>

$(function() {
  $("#preview").text($("#input1 option").length + " items");
});

不知道我能理解您其余的问题。


14

在多选选项框中,您可以$('#input1 :selected').length;用来获取所选选项的数量。如果未达到一定的最小数量的选项,这对于禁用按钮很有用。

function refreshButtons () {
    if ($('#input :selected').length == 0)
    {
        $('#submit').attr ('disabled', 'disabled');
    }
    else
    {
        $('#submit').removeAttr ('disabled');
    }
}

我发现这工作取下牙套后$('#input1 :selected').length; 支持文件api.jquery.com/length
伦纳德Kakande

6

好的,我有一些问题,因为我在

$('.my-dropdown').live('click', function(){  
});

我的页面内有多个,这就是为什么我使用一门课。

单击下拉列表时,我的下拉列表自动被ajax请求填充,因此我只有元素$(this)

所以...

我必须做:

$('.my-dropdown').live('click', function(){
  total_tems = $(this).find('option').length;
});

6

最好的形式是这样

$('#example option').length

该纯代码(低价值)解决方案由Sadikhasan于4年前提供。lengthKarim79在9年前发布了的使用。可以完全从页面中清除此答案,因为它是完全多余的。
mickmackusa

-1

可能有用的另一种方法。

$('#select-id').find('option').length

1
问题不是只要求选择 <option> s 的计数。
user4642212
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.