【问题标题】:How to get unselected or not selected options length from multiselect select dropdown如何从多选选择下拉列表中获取未选择或未选择的选项长度
【发布时间】:2018-10-18 02:14:52
【问题描述】:

我有一个多选下拉菜单,如下所示

<select id="mydd" multiple searchable="Search here..">
   <option value="" disabled selected>Choose your country</option>
   <option selected="selected" value="1">USA</option>
   <option selected="selected" value="2">Germany</option>
   <option selected="selected" value="3">France</option>
   <option value="4">Poland</option>
   <option selected="selected" value="5">Japan</option>
   <option value="6">Korea</option>
   <option selected="selected" value="7">India</option>
</select>

我想获取所有未选中选项(4 和 6)的长度。我试过了

$("#mydd option").not(":selected").length

这是不成功的。谁能解释为什么这不起作用?

【问题讨论】:

    标签: jquery dropdown multi-select content-length


    【解决方案1】:

    您的代码最初可以运行。运行 sn-p。

    看起来使用 .not() 检查 DOM 而不是当前标记。

    第一个警报包含您的代码,因为它们(DOM 和 HTML)呈现相同,所以可以正常工作。在某些事件之后,DOM 可能不等于浏览器中显示的 HTML。

    当您选择一个选项时,我使用了 另外 2 个提醒;一个使用 .not(),另一个使用 jquery 选择器

    请注意,当您单击某个选项时,HTML 不会被修改。具有选择属性的选项字段没有更改,它们仍然保持原样。 但在 DOM 中,选择的属性会被移除,只有点击的属性才会真正被“选中”。

    最后一个警报包含您的预期值。

    $(document).ready(function() {
      // initial
      alert("Initial; There are " + $("#mydd option").not(":selected").length + " not selected options.");
    
      // when an option is clicked, DOM itself would unselect the other options, but it doesn't modify the markup
      $("#mydd").click(function() {
        alert("Using .not; There are " + $("#mydd option").not(":selected").length + " not selected options.");
    
        // check if the 'selected' attribute exist
        alert("Using jquery selector; There are " + $("#mydd option:not([selected]").length + " not selected options.");
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <select id="mydd" multiple searchable="Search here..">
      <option value="" disabled selected>Choose your country</option>
      <option selected="selected" value="1">USA</option>
      <option selected="selected" value="2">Germany</option>
      <option selected="selected" value="3">France</option>
      <option value="4">Poland</option>
      <option selected="selected" value="5">Japan</option>
      <option value="6">Korea</option>
      <option selected="selected" value="7">India</option>
    </select>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-19
      相关资源
      最近更新 更多