Sorting Select box with jQuery

后端 未结 5 1826
情话喂你
情话喂你 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条回答
  •  孤城傲影
    2021-01-04 11:17

    Try this.

            $(document).ready(function()
            {
                var myarray=new Array();               
                $("select option").each(function()
                {
                    myarray.push({value:this.value, optiontext:$(this).text()});
                });
    
                myarray.sort(sortfun);
                $newHmtl="";
                for(var i=0;i"+myarray[i]['optiontext']+"";
                }
                $("select").html($newHmtl);
            });            
    
    
            function sortfun(a,b) 
            {
                a = a['value'];
                b = b['value'];                
                return a == b ? 0 : (a < b ? -1 : 1)
            }
    

提交回复
热议问题