Search code examples
jqueryjquery-select2-4jquery-select2

How to make a Select2 4.0 sortable?


I had this problem with the new version 4.0, and wasn't able to find any answer, until I myself solved with a work around after some hours of work.


Solution

  • My workaround solution:

    First, make it sortable with jquery.

    $("#mySelect").parent().find("ul.select2-selection__rendered").sortable({
        containment: 'parent',
        update: function() {
            orderSortedValues();
        }
    });
    

    The function orderSortedValues has the following idea: Change the order of the options of the original select input, and notifying select2 about the new order.

    orderSortedPassageValues = function() {
        $("#mySelect").parent().find("ul.select2-selection__rendered").children("li[title]").each(function(i, obj){
            var element = $("#mySelect").children("option[value="+obj.title+"]");
            moveElementToEndOfParent(element)
        });
    };
    
    moveElementToEndOfParent = function(element) {
        var parent = element.parent();
    
        element.detach();
    
        parent.append(element);
    };
    

    Finally, it will also be necessary to stop the automatic sorting with selecting a new value through the dropdown

    stopAutomaticOrdering = function() {    
        $("#mySelect").on("select2:select", function (evt) {
            var id = evt.params.data.id;
    
            var element = $(this).children("option[value="+id+"]");
    
            moveElementToEndOfParent(element);
    
            $(this).trigger("change");
        });
    }
    

    PS: the scope of the functions are global. You may change it... Hope to help someone else.