简体   繁体   中英

Select2 multiselect - How to stop automatic sorting?

When you select multiple items, they are sorted alphabetically. We would like to preset the select order without sorting. That means, if I select "B" and then "A", the multi select should display "B", "A" and not "A", "B". How to achieve that?

<select id="multiple" class="form-control select2-multiple" multiple>
<optgroup label="Alaskan">
<option value="A">A</option>
<option value="B">B</option>
</optgroup>
</select>

Thanks.

There is a soluition 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>

Source

选择的顺序是正确的,但改变了列表中的顺序!

Use this when selecting is ok!

$("select").on("select2:select", function (evt) {
  var element = evt.params.data.element;
  var $element = $(element);

  $element.detach();
  $(this).append($element);
  $(this).trigger("change");
});

but server rendering will auto sorting... so maybe try this way

var serverRenderData = ['D', 'B'];
//usually we render data by this way, but select2 will auto sorting
$("select").val(serverRenderData).trigger('change');

//so we re-append select data
var options = [];
for (var i = 0; i < serverRenderData.length; i++) {
    options.push($("select option[value=" + serverRenderData[i] + "]"));
}
$("select").append(...options).trigger('change');

jsFiddle demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM