MicTech
MicTech

Reputation: 45083

Sorting items in Select with remember what is selected

I wanted to sorting items in select, but all solution what I finded have selecting last item in select. And it's problem if you edit existing data in forms.

How solve this?

Please don't ask me, why I didn't sorting items at server side.

Upvotes: 1

Views: 147

Answers (1)

MicTech
MicTech

Reputation: 45083

My Solution

    function sortValues() {
        var sortedValues = $.makeArray($('.selectSort option')).sort(function(a, b) {
            return $(a).text() > $(b).text() ? 1 : -1;
        });
        $('.selectSort').empty().html(sortedValues);
    };

    $(document).ready(function() {
        var selected = $(".selectSort option:selected").val();
        sortValues();
        if (!$(".selectSort option:selected").length) {
            $(".selectSort").val(0);
        } else {
            $(".selectSort").val(selected);
        }
    });

Upvotes: 1

Related Questions