Friday, November 19, 2010

Sorting items in the html select/list box using javascript

How to Sort the items in the list box based on the text

function
sortListBox(box)
{
var
temp_opts = new Array();
var temp = new Object();
for(var i = 0; i < box.options.length; i++)
{
temp_opts[i] = box.options[i];
}
for
(var x = 0; x < temp_opts.length - 1; x++)
{
for
(var y =(x + 1); y < temp_opts.length; y++)
{
if
(temp_opts[x].text > temp_opts[y].text)
{
tempT = temp_opts[x].text;
tempV = temp_opts[x].value;
temp_opts[x].text = temp_opts[y].text;
temp_opts[x].value = temp_opts[y].value;
temp_opts[y].text = tempT;
temp_opts[y].value = tempV;
}
}
}
for
(var i = 0; i < box.options.length; i++)
{
box.options[i].text = temp_opts[i].text;
box.options[i].value = temp_opts[i].value;
}
}

1 comment: