Select2: How to prevent tags sorting

后端 未结 3 431
臣服心动
臣服心动 2020-12-03 10:51

When user selects many items (tags), they are automatically sorted alphabetically. How to prevent automatic sort and keep user\'s order using Select2 4.0?

Update:

相关标签:
3条回答
  • 2020-12-03 11:07

    This has been discussed before for Select2 3.5.2, you can use select2('data') to get the order.

    $("select").select2();
    
    $('#sayResult').click(function () {
      // 'data' brings the unordered list, while val does not
      var data = $('select').select2('data');
      
      // Push each item into an array
      var finalResult = data.map(function () {
        return this.id;
      });
    
      // Display the result with a comma
      alert( finalResult.join(',') );
    });
    <link href="//cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.css" rel="stylesheet"/>
    
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.js"></script>
    
    <select style="width: 500px;" multiple="multiple">
      <option>two</option>
      <option>four</option>
      <option>six</option>
    </select>
    
    <button id='sayResult'>Say Result</button>

    0 讨论(0)
  • 2020-12-03 11:08

    I've found a solution that works with Select2 v4. It changes the order of items - item selected by user are moved to the end.

    $("select").select2();
    
    $("select").on("select2:select", function (evt) {
      var element = evt.params.data.element;
      var $element = $(element);
      
      $element.detach();
      $(this).append($element);
      $(this).trigger("change");
    });
    <link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.css" rel="stylesheet"/>
    
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.js"></script>
    
    <select style="width: 500px;" multiple="multiple">
      <option>two</option>
      <option>four</option>
      <option>six</option>
    </select>

    Update

    The solution was found here: github.com/select2/select2/issues/3106. Its author is kevin-brown.

    0 讨论(0)
  • 2020-12-03 11:21

    This solution works best

    HTML

    <select style="width: 500px;" multiple="multiple">
        <option>two</option>
        <option>four</option>
        <option>six</option>
      </select>
    

    JS

    $(document).ready( function () {
    
        $("select").select2({
          tags: true
        });
        
        $("select").on("select2:select", function (evt) {
          var element = evt.params.data.element;
          var $element = $(element);
          
          $element.detach();
          $(this).append($element);
          $(this).trigger("change");
        });
    
    } );
    
    0 讨论(0)
提交回复
热议问题