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.
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.
Share Improve this question edited Nov 23, 2016 at 11:53 Vedang asked Nov 23, 2016 at 11:25 VedangVedang 1591 silver badge8 bronze badges 1- 2 Post your code. – Mihai Alexandru-Ionut Commented Nov 23, 2016 at 11:26
2 Answers
Reset to default 12There 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./ajax/libs/select2/4.0.0/css/select2.css" rel="stylesheet"/>
<script src="//cdnjs.cloudflare./ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare./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
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1743604868a4477669.html
评论列表(0条)