sort items in a dropdown list without the first item

后端 未结 6 1017
粉色の甜心
粉色の甜心 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:34
    function sortDropDownListByText(selectId) {
        var foption = $('#'+ selectId + ' option:first');
        var soptions = $('#'+ selectId + ' option:not(:first)').sort(function(a, b) {
           return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
        });
        $('#' + selectId).html(soptions).prepend(foption);              
    
    };
    

    is your function.

    0 讨论(0)
  • 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); 
    
    0 讨论(0)
  • 2021-01-04 03:47

    Remove the first item from the select box and then append it at the first position after the sort function.

    $(selectId).html($(selectId + " option:not(':first-child')").sort(function(a, b) {
           return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
        }))
    
    0 讨论(0)
  • 2021-01-04 03:54

    How about always returning -1 for that item?

    $(selectId).html($(selectId + " option").sort(function(a, b) {
       return a.text == "Please select an item from the list" ? -1 : a.text < b.text ? -1 : 1;
    });
    

    more dynamically:

    $(selectId).html($(selectId + " option").sort(function(a, b) {
       return a.text == $(selectId + 'option:first').text ? -1 : a.text < b.text ? -1 : 1;
    });
    
    0 讨论(0)
  • 2021-01-04 03:55

    If the "Please select..." option has a certain value (here called "dummyVal") associated with it, you could use this in your comparison function:

    function sortDropDownListByText(selectId, dummyVal) {
        $(selectId).html($(selectId + " option").sort(function(a, b) {
            if (a.value == dummyVal) {
                return -1;
            }
            return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
        })) 
    }
    
    0 讨论(0)
  • 2021-01-04 03:57

    Theoretically, I would approach the problem by removing the "Please select" entry, sorting the list, then append it again, once the sorting is done

    0 讨论(0)
提交回复
热议问题