Select2: How to prevent tag sorting

When a user selects a lot of elements (tags), they are automatically sorted in alphabetical order. How to prevent automatic sorting and save user order with Select2 4.0?

Update:

The mentioned "possible duplication question" refers to an older version of Select2 v3 ... I ask about version 4 ... It differs in the form of the older ones, and the answers mentioned do not solve the problem.

+8
jquery jquery-select2
source share
2 answers

I found a solution that works with Select2 v4. It changes the order of the elements - the element selected by the user moves 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 is found here: github.com/select2/select2/issues/3106 . Its author is Kevin Brown.

+19
source share

This one was 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> 
+1
source share

All Articles