开发者

sort entries of a drop down alphabitically

开发者 https://www.devze.com 2023-02-12 01:39 出处:网络
I am dynamically adding drop entries to a drop down by using following code. var x =document.getElementById(\"x\");

I am dynamically adding drop entries to a drop down by using following code.

var x =document.getElementById("x");
v开发者_JAVA技巧ar optn = document.createElement("OPTION");
optn.text="hhh";  
optn.value="val";  
x.add(optn);  

The above thing is done in a loop Now i want to sort it alphabatically.How can i do it?


It would be easier to sort the array before adding the options to the dropdown. Moving DOM elements around once they are added would be less efficient. For example:

var arr = [ { id: '1', value: 'B' },
            { id: '2', value: 'A' },
            { id: '3', value: 'C' } ];
arr.sort(function(a, b) {
    if (a.value < b.value) {
        return -1;
    }
    if (a.value > b.value) {
        return 1;
    }
    return 0;
});

for (var i = 0; i < arr.length; i++) {
    // TODO: the array is now sorted => build the dropdown here
}


public void SortDropDownList(DropDownList ddl)
{
    //create a ListItem array the size of the items
    //in your DropDownList
    ListItem[] sorted = new ListItem[ddl.Items.Count];
    //loop through all the items in your ListItem array
    for (int i = 0; i < sorted.Length; i++)
    {
        //resize the array on each iteration
        Array.Resize(ref sorted, i);
        //add the current index to the array
        sorted[i] = ddl.Items[i];
    }
    //call Array.Sort to sort your ListItem array
    Array.Sort(sorted);
    //remove all items from the DropDownList
    ddl.Items.Clear();
    //add the sorted items to the DropDownList
    ddl.Items.AddRange(sorted);
}

u use the help of this function after the all items bound to the dropdownlist

0

精彩评论

暂无评论...
验证码 换一张
取 消