DelphiFAQ Home Search:

Sorting a SELECT listbox in Javascript

 

comments39 comments. Current rating: 5 stars (19 votes). Leave comments and/ or rate it.

Question:

What is the best way to sort a SELECT list box in Javascript?

Answer:

The following example assumes that your text and value tags are the same. In this case you can build an array of all the texts, use Javascript's built-in sort() function and the update the listbox.
You don't even need to clear the listbox and then populate it again (which would be slower and possibly cause flickering). Instead you can update each entry directly.

See the script live here (click on "Sort" below the list):

<script language="JavaScript" type="text/javascript">
function sortlist() {
var lb = document.getElementById('mylist');
arrTexts = new Array();

for(i=0; i<lb.length; i++)  {
  arrTexts[i] = lb.options[i].text;
}

arrTexts.sort();

for(i=0; i<lb.length; i++)  {
  lb.options[i].text = arrTexts[i];
  lb.options[i].value = arrTexts[i];
}
}
</script>


<form action="#">
<select name=mylist id=mylist size=5>
<option value="Anton">Anton
<option value="Mike">Mike
<option value="Peter">Peter
<option value="Bill">Bill
<option value="Carl">Carl
</select>
<br>
<a href="javascript:sortlist()">sort</a>
</form>

Content-type: text/html

Comments:

You are on page 2 of 3, other pages: 1 [2] 3
2007-05-31, 16:48:08
info@abakosolutions.com from Guayaquil, Ecuador  
rating
Very useful script.

You can make it more general by replacing:

function sortlist()

with

function sortlist(list)

and

var lb = document.getElementById('mylist');

with

var lb = document.getElementById(list);


2007-07-18, 09:43:38
anonymous  
Great... thanks a lot
2007-09-06, 11:42:46
gurkjis from Latvia  
rating
In place of:
lb.options[i].text = arrTexts[i];


better use:
lb.options[i].innerHTML = arrTexts[i];


because IE6 throws 'Unspecified error' if above sorting was called appendChild to Select element.
2007-09-24, 11:32:36
anonymous from United States  
dwp:

Your dorky 'one-liner' lacks something crucial when it comes to wide distribution of code: readability! (thus maintainability)


2008-01-30, 13:05:56
[hidden] from Los Angeles, United States  
rating
I love it when you paste a script and it works the first time. Great script! thanks man!
2008-04-20, 07:51:05
anonymous from Germany  
why you writing the option tags new ?

function sortItems(obj)
{
var b = new Array();
var c = obj.getElementsByTagName('option');
for ( var i in c )
{
try {
if (c[i].hasAttribute('value'))
b.push( new Array( c[i].text, obj[i].cloneNode(true) ) );
} catch(e) { continue; }
}
b.sort();
for ( var i in c )
{
try {
if (c[i].hasAttribute('value'))
{
var d = b.shift();
obj.replaceChild(d[1],c[i]);
}
} catch(e) { continue; }
}
}
2008-05-20, 00:11:42
anonymous from United States  
What a waste of space. If you use the prototype base library here is a one liner.


Yeah, and if you include the code that allows the function to work it is very far from a one liner!!!
2008-06-05, 13:28:11
anonymous from United States  
Thank you so MUCH!
2008-06-12, 07:14:07
anonymous from Canada  
rating
This has all been very helpful. I built off of it, and it turns out that a 2-dimensional array sorts quite easily, and I feel that it is a much safer way to sort when you have different TEXT and VALUE entries than using split, since split means you can't use the seperator character in your entries. Here is my code:

function sortCompanys(form){
var tempSort = new Array();
for(i=1; i<form.company.length; i++){
tempSort[i-1] = new Array();
tempSort[i-1][0] = form.company.options[i].text;
tempSort[i-1][1] = form.company.options[i].value;
}
var selectedValue = form.company.options[form.company.selectedIndex].value;
tempSort.sort();
for(i=1; i<form.company.length; i++){
form.company.options[i].text = tempSort[i-1][0];
form.company.options[i].value = tempSort[i-1][1];
if(form.company.options[i].value == selectedValue){
form.company.selectedIndex = i;
}
}
}

The 'i-1' is there because my FIRST entry is 'All Companies' which I do not want to have sorted. If you wish for ALL entries to be sorted, just use 'i' and make sure the for loop starts with 0 instead of 1. Another nice feature of this code is that it will remember the current selection, and when it resorts, it will make sure the selection remains constant.

Enjoy :)
2008-07-30, 06:24:53
anonymous from New Delhi, India  
rating
2008-07-30, 06:25:20
anonymous from India  
GOOD ONE
2008-08-08, 00:19:01
anonymous  
How to sort textbox array and set the label in the jsp depending on the sort value


2008-10-03, 16:23:30
HainKurt from United States  
Here is another function which is a mix of aboves, which

support for number of fixed elements on top not to be sorted
support for sort option (text/value)

function SortList(myList, fixedElements, opt){
// opt = 0 : sort by text, default
// opt = 1 : sort by value
opt = (opt?opt:0)
fixedElements = (fixedElements?fixedElements:0)

var tempSort = new Array();
for(i=fixedElements; i<myList.length; i++){
tempSort[i-fixedElements] = new Array();
if (opt==0){
tempSort[i-fixedElements][0] = myList.options[i].text;
tempSort[i-fixedElements][1] = myList.options[i].value;
} else {
tempSort[i-fixedElements][0] = myList.options[i].value;
tempSort[i-fixedElements][1] = myList.options[i].text;
}
}

var selectedValue = myList.options[myList.selectedIndex].value;
tempSort.sort();

for(i=fixedElements; i<myList.length; i++){
if (opt==0){
myList.options[i].text = tempSort[i-fixedElements][0];
myList.options[i].value = tempSort[i-fixedElements][1];
} else {
myList.options[i].value = tempSort[i-fixedElements][0];
myList.options[i].text = tempSort[i-fixedElements][1];
}
if(myList.options[i].value == selectedValue){
myList.selectedIndex = i;
}
}
}

call it on a button like

                    <img src='img/sort1.gif' width='16' height='16' OnClick='SortList(lstAppls,2,0)' style='cursor:hand' alt='sort by text'/>
                    <img src='img/sort2.gif' width='16' height='16' OnClick='SortList(lstAppls,2,1)' style='cursor:hand' alt='sort by value'/>

thanks...
2009-02-10, 17:42:35
[hidden] from Glen Burnie, United States  
Hi,

Thank you so much for the post and the modified versions. You guys are the best!
2009-02-10, 17:43:33
anonymous from United States  
rating
You are on page 2 of 3, other pages: 1 [2] 3

 

 

NEW: Optional: Register   Login
Email address (not necessary):

Rate as
Hide my email when showing my comment.
Please notify me once a day about new comments on this topic.
Please provide a valid email address if you select this option, or post under a registered account.
 

Show city and country
Show country only
Hide my location
You can mark text as 'quoted' by putting [quote] .. [/quote] around it.
Please type in the code:

Please do not post inappropriate pictures. Inappropriate pictures include pictures of minors and nudity.
The owner of this web site reserves the right to delete such material.

photo Add a picture: