Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 234
Lucas Vieira Avatar asked Jan 02 '26 05:01

Lucas Vieira


1 Answers

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.

like image 93
Lucas Vieira Avatar answered Jan 04 '26 09:01

Lucas Vieira



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!