Sorting dropdown list using Javascript

前端 未结 7 965
孤城傲影
孤城傲影 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:39

    The answers provided didn't really suit my case so I made my own (especially not wanting jQuery). Figured it might help others.

    sortDropDown(document.querySelector('select'));
    
    function sortDropDown(d){
        //save option values
        var existingOptions=d.options; 
    
        //keep track of previously selected option
        var selectedOpt=d.selectedOptions[0].value;
    
        //turn nodeList into Array of values
        existingOptions=[].slice.call(existingOptions).map(function(a){return a.innerText});
    
        //make sure options are unique
        existingOptions = existingOptions.filter( function(value, index, self) { 
            return self.indexOf(value) === index;
        }); 
    
        //sort options
        existingOptions.sort();
    
        //keep "All" option as first element
        existingOptions.splice(0, 0, existingOptions.splice(existingOptions.indexOf('All'), 1)[0]);
    
        //repleace dropdown contents
        var t='';
        existingOptions.forEach(function(a){
            t+='';
        });
        d.innerHTML=t;
    }
    

提交回复
热议问题