Sorting dropdown list using Javascript

前端 未结 7 972
孤城傲影
孤城傲影 2020-11-27 17:02

i want to sort the drop down items using javascript,can anyone tell me how to do this.

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-27 17:49

    FOR DROPDOWN FOR WHOLE PROJECT

    $(document).ready(function () {
        $.when($('select').addClass('auto-drop-sort')).then($.fn.sortDropOptions("auto-drop-sort"))
    })
    
    /*sort all dropdown*/
    $.fn.sortDropOptions = function(dropdown_class){
        var prePrepend = ".";
        if (dropdown_class.match("^.") == ".") prePrepend = "";
        var myParent = $(prePrepend + dropdown_class);
        $.each(myParent, function(index, val) {
            /*if any select tag has this class 'manual-drop-sort' this function wont work for that particular*/
            if ( ! $(val).hasClass('manual-drop-sort') ) {
                var selectedVal = $(val).val()
                $(val).html($(val).find('option').sort(
                    function (a, b) {
                        if ( a.value != -1 && a.value != 0 && a.value != '' ) {
                            return a.text == b.text ? 0 : a.text < b.text ? -1 : 1 
                        }
                    })
                );
                $(val).val(selectedVal)
            }else{
                /* set custom sort for individual select tag using name/id */
            }
        });
    }
    

提交回复
热议问题