【问题标题】:How to limit number of displayed tags in select2?如何限制select2中显示的标签数量?
【发布时间】:2020-03-10 17:15:30
【问题描述】:

我需要限制显示的选定标签的数量。请注意,我不想限制所选标签的最大数量。因此,用户应该能够根据需要选择尽可能多的选项,但我想控制所选标签的显示方式。

例如,我可能只想显示如下文本:5 items are selected。 我尝试使用templateSelection 配置参数,但是这个函数是按选定的选项调用的,所以我不能为多个选定的选项返回一个标签。

我还找到了this 的答案,但它不起作用(在更改回调中设置 html 没有任何作用)而且它看起来更像是一个 hack。

是否有一些内置的或更好的方法来实现它?

【问题讨论】:

    标签: javascript jquery html jquery-select2


    【解决方案1】:

    最后,我找到了this great article 关于适配器,其中还包含工作的 jsfiddle。

    【讨论】:

      【解决方案2】:

      在此示例中,您可以使用条件if (selected > 4) 定义要在选择多少后显示文本。或者删除该条件以显示任何输入的文本。

      $("#singleSelectExample").select2({
        closeOnSelect: false
      });
      
      $("#singleSelectExample2").select2();
      
      $('#singleSelectExample').on('change', function() {
        var selected = $(this).val().length;
        var of = $(this).find('option').length;
      
        if (selected > 4)
          $(this).parent().find('.select2 .select2-selection ul').html('Selected ' + selected + ' of ' + of +'  items.')
      });
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
      <link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet" />
      <script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>
      
      <select id="singleSelectExample" multiple style="width: 300px;">
        <option value="1">Option 1</option>
        <option value="2">Option 2</option>
        <option value="3">Option 3</option>
        <option value="4">Option 4</option>
        <option value="5">Option 5</option>
        <option value="6">Option 6</option>
        <option value="7">Option 7</option>
        <option value="8">Option 8</option>
        <option value="9">Option 9</option>
        <option value="10">Option 10</option>
      </select>

      【讨论】:

        猜你喜欢
        • 2014-02-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-01
        • 2021-09-26
        相关资源
        最近更新 更多