sort items in a dropdown list without the first item

后端 未结 6 1108
粉色の甜心
粉色の甜心 2021-01-04 02:59

I have the following code to sort the items in a dropdown list:

function sortDropDownListByText(selectId) {
    $(selectId).html($(selectId + \" option\").so         


        
6条回答
  •  旧巷少年郎
    2021-01-04 03:39

    First you have to preserve the selected value, and once you finished the sorting you re-select the preserved value.

    #store the selected value.
    var selectedVal = $(selectId).val(); 
    
    # start sorting.
    $(selectId).html( $(selectId+" option").sort(function(a, b) {
           return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
        }));
    
    #re-select the preserved value.
    $(selectId).val(selectedVal); 
    

提交回复
热议问题