Sorting Select box with jQuery

后端 未结 5 1921
情话喂你
情话喂你 2021-01-04 10:20

I have a select box on a form, which carries an incremental rel attribute. I have a function that can sort the options by thier .text() value, into alphabetcal order.

<
5条回答
  •  旧时难觅i
    2021-01-04 11:10

    For future reference, the accepted answer is not complete if option has data or props (e.g. .prop('selected', true)). They will be removed after using .html().

    The function below is probably not optimized but it's correctly working :

    $.fn.sortChildren = function(selector, sortFunc) {
        $(this)
        .children(selector)
        .detach()
        .sort(sortFunc)
        .appendTo($(this));
    };
    
    $('select').sortChildren('option', function(a, b) {
        // sort impl
    });
    

提交回复
热议问题