jQuery 计算选择下拉列表中的选项数量(同一页面上有多个)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8951931/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 11:18:52  来源:igfitidea点击:

Counting the number of options in a select drop down (multiple on same page)

jquery

提问by Matt Price

I am trying to output the number of options in a select drop down, but there are multiple ones on the same page.

我试图在选择下拉列表中输出选项数量,但同一页面上有多个选项。

For example:

例如:

<select name="select" class="drop">
   <option name="option" value="Option 1"></option>
</select>

<select name="select" class="drop">
   <option name="option" value="Option 1"></option>
   <option name="option" value="Option 2"></option>
   <option name="option" value="Option 3"></option>
</select>

So the first one would output (1) and the second would output (3).

所以第一个输出(1),第二个输出(3)。

I have this code but it outputs (4) - counting all options from all selects.

我有这个代码,但它输出 (4) - 计算所有选择中的所有选项。

<script type="text/javascript">
$(function() {
   $(".date_number").text($(".drop option").length + " items");
});
</script>

Any help appreciated!

任何帮助表示赞赏!

回答by Didier Ghys

Using the selector ".drop option"will get allthe optionelements under(not necessarily direct children) of an element with class ".drop".

使用选择".drop option"会得到所有option元素与元素的类(不一定是直接的子女)".drop"

Note that this does not only is valid for select element but also with this:

请注意,这不仅对 select 元素有效,而且对以下内容有效:

<div class="drop">
    <select>
        <option>Item 1</option>
        <option>Item 2</option>
        <option>Item 3</option>
    </select>
</div>

$('.drop option').length // 3

To ensure your <option>elements children of <select class="drop">, use the children selector >:

为确保您的<option>元素为 的子元素<select class="drop">,请使用子选择器>

$('.drop > option');


To get separately the amount of options for each select, you would select the <select>first and then count for each of then. You can do something like:

要分别获得每个选择的选项数量,您可以选择第<select>一个,然后为每个选择计数。您可以执行以下操作:

var optionsArr = $('select.drop').map(function() {
                     return $(this).find('option:not(:disabled)').length;
                 }).toArray();

This will return an array with the different amounts: [1, 3]

这将返回一个具有不同数量的数组: [1, 3]

DEMO

演示



To add a div with the the text "3 date(s) available", do this:

要添加带有文本“3 个可用日期”的 div,请执行以下操作:

$('select.drop').each(function() {
    // the current select.drop
    var $this = $(this);
    // create a div with the text you want
    $('<div>' + $this.find('option:not(:disabled)').length + ' date(s) available</div>')
        // append it after the current select.drop
        .insertAfter($this);
});

///////////////////////

///////////////////////

Ok, nearly there! Thanks again for your time on this...

好的,快到了!再次感谢您抽出宝贵时间...

I have put the code in and it is doing what I want it to do, however due to the fact that it is all in an Accordion, it loops each time for each accordion item. See screenshot (excuse styling):

我已经把代码放进去了,它正在做我想要它做的事情,但是由于它全部在一个手风琴中,它每次都为每个手风琴项目循环。见截图(借口样式):

Screenshot

截屏

I just need it to now only loop for the select drop in that accordion, rather than for each one.

我只需要它现在只循环选择那个手风琴中的下拉,而不是每个。

Also, in my Select fro down, I have the first Option as "Disabled" as part of the validation so that the user has to select an item before continuing, such as:

此外,在我的“选择”中,我将第一个选项设置为“已禁用”作为验证的一部分,以便用户在继续之前必须选择一个项目,例如:

<option disabled="disabled"></option>

The javascript is also counting this. So is there any way we can put a -1 in there to the result, or is there a better way of doing this that I am missing?

javascript 也在计算这个。那么有什么方法可以让我们在结果中加入 -1,或者有没有更好的方法来做到这一点,但我缺少什么?

Thanks again...

再次感谢...

回答by Suissa

It′s very easy, you only have to get length value from option:selected, like this:

这很简单,你只需要从 option:selected 中获取长度值,就像这样:

$('.drop option:selected').length

$('.drop option:selected').length

I hope this be useful.

我希望这很有用。

回答by dknaack

Description

描述

You get 4because your jQuery selector matches for all the options on your page.

你得到4是因为你的 jQuery 选择器匹配你页面上的所有选项。

The basic question is, which selectyou want count ?

基本问题是,select您想要计数哪个?

The best, for search engine optimization (for example), is you give the selects different ids. But you can use other jQuery selectors like :eq(), :first, :lastor otherl too. It depends on what you want to do.

最好的,对于搜索引擎优化(例如),是你给选择不同的 id。但是你可以使用其他jQuery选择喜欢的:eq():first:last或otherl过。这取决于你想做什么。

Samples

样品

Different IDs's

不同的ID

<select id="select1" name="select" class="drop">
   <option name="option" value="Option 1"></option>
</select>

<select id="select2" name="select" class="drop">
   <option name="option" value="Option 1"></option>
   <option name="option" value="Option 2"></option>
   <option name="option" value="Option 3"></option>
</select>

<span class="date_number"/>

$(function() {
  $(".date_number").text($("#select2 option").length + " items")
});

Check out this jsFiddle Demonstration

看看这个jsFiddle 演示

:last Selector

:last 选择器

$(function() {
    $(".date_number").text($(".drop:last option").length + " items")
});

Check out this jsFiddle Demonstration

看看这个jsFiddle 演示

More Information

更多信息

回答by redronin

Since you don't have a unique id for each select, you'd have to do something like:

由于您没有每个选择的唯一 ID,因此您必须执行以下操作:

$('.drop').text( function(){
  console.log($(this).select('option').length);
  // instead of console.log return the text you want
  // return $(this).select('option').length + " items";
});

What this does is for each .drop class, it runs the function defined. The function is find all the elements scoped within $(this). $(this) is the current .drop class element.

这是为每个 .drop 类做的,它运行定义的函数。该函数是查找 $(this) 范围内的所有元素。$(this) 是当前的 .drop 类元素。

And the $('.drop') will run for every .drop class it finds.

并且 $('.drop') 将针对它找到的每个 .drop 类运行。