sharafjaffri
sharafjaffri

Reputation: 2214

sort select element options and preserve focus

I am trying to write script that will sort all select elements on page and preserve selected element selected. I have worked and implemented function given below. this function works well for sorting but lost focus of selected Text, because source of rendered page suggest that earlier selected item is still selected but focus is set to last item.

       var bindSortselect= function(){
           $("select").each(function(){
               $(this).html($(this).children("option").sort(function (a, b) {
                 if (a.text.toUpperCase() == b.text.toUpperCase()) return 0;
                 if (a.text.toUpperCase() < b.text.toUpperCase()) return -1;
                 if (a.text.toUpperCase() > b.text.toUpperCase()) return 1;
               }));
          });
        };

Any Idea would be appreciated?

Upvotes: 0

Views: 139

Answers (1)

Niranjan Borawake
Niranjan Borawake

Reputation: 1638

You just need to retain the selected option and set it again after you sort the options. Check this fiddle.

Upvotes: 2

Related Questions