Advertise with us

How to sort multiselected items?

I have already finished the function of grouping the selected items and unselected items, but I need to sort them in alphabetic order meanwhile. My js code is shown below:

$("#id").multiselect({
        beforeopen: function (event, ui) {
            var selected = $("#id option:selected");
            selected.remove();
            $("#id").prepend(selected);
            $("#id").multiselect('refresh');
        }
    });

How can I achieve this?

Last updated:10/31/2014 12:54:32 AM

1 Answers

Barbara Jones
Barbara Jones

Here's a nice(-ish) way to do it:



$("#clickity").click(function () {
        $("#derp>span").sort(function (a, b) {
            return (a.textContent ||a.innerText).localeCompare(b.textContent || b.innerText);
        }).prependTo("#derp");
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="derp"><span>g</span><span>o</span><span>t</span><span>h</span><span>s</span></div>
<button id="clickity">Sort!</button>

Answer