DelphiFAQ Home Search:

Sorting a SELECT listbox in Javascript

 

comments25 comments. Current rating: 5 stars (14 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>

Comments:

You are on page 1 of 2, other pages: [1] 2
2006-06-19, 12:16:04
anonymous from United States  
this works great. nice and simple. thanks!

2006-08-09, 17:47:04
anonymous from United States  
rating
Here i have modified little bit this code..

If text and value tags are different, sorting only text. Keeping the same value for the corresponding test.

function sortList()
{
var lb = document.getElementById('mylist');
arrTexts = new Array();
arrValues = new Array();
arrOldTexts = new Array();

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

arrOldTexts[i] = lb.options[i].text;
}

arrTexts.sort();

for(i=0; i<lb.length; i++)
{
lb.options[i].text = arrTexts[i];
for(j=0; j<lb.length; j++)
{
if (arrTexts[i] == arrOldTexts[j])
{
lb.options[i].value = arrValues[j];
j = lb.length;
}
}
}
}
2006-08-14, 14:57:47
anonymous from United States  
rating
thanks!
2006-11-16, 08:53:10
anonymous from Canada  
rating
Thank you very much, also to the person that modified the code (2006-8-9)
2006-11-29, 16:16:28
varsovie from Poland  
rating
2006-08-09, 17:47:04
there is mistake in first line - function SortLine !!!!!!! <- case sensitive Line=/=line
I spent 30minutes on it - i'm not js programmer
Work fine - very helpful for people using flat base like *.txt not having access for SQL etc

i add some keyowrds for GOOGLE for faster searching:
HOW TO SORT SELECT OPTION IN HTML UNDER JAVASCRIPT
SORTING <option> JS in HTML FORM
2006-12-07, 09:35:29
David Carty Wigan Lancs from United Kingdom  
<head>
</head>
<body>
<script language='JavaScript' type='text/javascript'>
function compareText (opt1, opt2) {
// not case sensitive
return opt1.text.toLowerCase() < opt2.text.toLowerCase() ? -1 :
opt1.text.toLowerCase() > opt2.text.toLowerCase() ? 1 : 0;
}

function compareTextCaseSensitive (opt1, opt2) {
// case sensitive
return opt1.text < opt2.text ? -1 :
opt1.text > opt2.text ? 1 : 0;
}

function SortListBox (pListBox, compareFunction) {
if (!compareFunction)
compareFunction = compareText;
var options = new Array (pListBox.options.length);
for (var i = 0; i < options.length; i++)
options[i] =
new Option (
pListBox.options[i].text,
pListBox.options[i].value,
pListBox.options[i].defaultSelected,
pListBox.options[i].selected
);
options.sort(compareFunction);
pListBox.options.length = 0;
for (var i = 0; i < options.length; i++)
pListBox.options[i] = options[i];
}
</script>
<form name='Form1' method='post'>

<select name='ListBox1' size='10' id='ListBox1' >
<option value='Wigan'>Wigan</option>
<option value='David'>David</option>
<option value='Lancashire'>Lancashire</option>
<option value='Michelle'>Michelle</option>
<option value='Hilda'>Hilda</option>
<option value='Ron'>Ron</option>
<option value='Jack'>Jack</option>
<option value='Anthony'>Anthony</option>
<option value='albert'>albert</option>
</select>
<INPUT TYPE='button' VALUE='sort' onClick='SortListBox(document.Form1.ListBox1, compareText)' >
</form>
</body>
</html>
2006-12-07, 15:53:17
anonymous from United States  
how abt sorting a listbox based on culture (locale)

thanks and regards,
2006-12-22, 16:33:34
dwp from United States  
rating
What a waste of space. If you use the prototype base library here is a one liner.

$A(sb.options).sort(function(a,b){ return (a.text.toLowerCase() < b.text.toLowerCase() ) ?
-1 : 1; }).each(function(o,i){ sb.options[i] = o;});
2007-01-11, 14:59:42
anonymous from Turkey  
nice work!
2007-01-29, 08:53:48
mishake@xlay.net from Romania  
here's a function, just with a small modification to the first posted. It's sorting options in a select, preserving their values
------------------
            function sortlist(id) {
                var lb = document.getElementById(id);
                arrTexts = new Array();

                for(i=0; i<lb.length; i++) {
                    arrTexts[i] = lb.options[i].text+':'+lb.options[i].value;
                }
                arrTexts.sort();
                for(i=0; i<lb.length; i++) {
                    el = arrTexts[i].split(':');
                    lb.options[i].text = el[0];
                    lb.options[i].value = el[1];
                }
            }
2007-02-03, 04:06:33   (updated: 2007-02-03, 04:08:46)
David,Carty,Wigan,Lancs from United Kingdom  
rating
Admittedly dwp’s contribution is a neat and applicable solution to the original issue. It saves coding time and utilises a standards-compliant library. If you are not already familiar with prototype.js then the information contained at the following link should provide a useful introduction: http://www.sergiope..pe.js.html
2007-02-17, 05:04:05
anonymous from India  
Hi,
I have a server side DropDownlistbox.. When a page loads I have some data binded to the Dropdownlistbox.I want to bind different data to the dropdownlist when I check a checkbox. Pls can any1 help me...
2007-03-20, 07:32:55
Bhavani,P,Polimetla from United States  
rating
Hi,

Here is modified tested script as on March-2007. This also retains the default selected value.

function listSort(id) {
            var lb=id;
            var oldValue = id[id.selectedIndex].value;

            arrTexts = new Array();

            for(i=0; i<lb.length; i++) {
                arrTexts[i] = lb.options[i].text+':'+lb.options[i].value;
            }
            arrTexts.sort();
            for(i=0; i<lb.length; i++) {
                el = arrTexts[i].split(':');
                lb.options[i].text = el[0];
                lb.options[i].value = el[1];

                if(oldValue == lb.options[i].value)
                    lb.options[i].selected = true;
                else
                    lb.options[i].selected = false;
            }
}

Bhavani P Polimetla
2007-03-20, 07:42:03
Bhavani,P,Polimetla from United States  
rating
here is the final code with Exception handling. Thank you for giving basic code.

function listSort(idGiven) {
            var lb=idGiven;
            var oldValue;

            try
            {
            oldValue = lb[lb.selectedIndex].value;

            arrTexts = new Array();

            for(i=0; i<lb.length; i++) {
                arrTexts[i] = lb.options[i].text+':'+lb.options[i].value;
            }
            arrTexts.sort();
            for(i=0; i<lb.length; i++) {
                el = arrTexts[i].split(':');
                lb.options[i].text = el[0];
                lb.options[i].value = el[1];

                if(oldValue == lb.options[i].value)
                    lb.options[i].selected = true;
                else
                    lb.options[i].selected = false;
            }

            }catch(e)
            {
            //In case of any error, dont do anything.
            alert('The following error occurred: ' + e.name + ' - ' + e.message);
            lb=idGiven;
            }

}

Bhavani P Polimetla
2007-03-20, 09:36:09
[hidden] from Germany  
rating
you don't need the JavaScript Library Prototype for a handy one-liner. Just use the Array sort function directly from the Array.prototype object and call it in the scope of the options you want to sort. Works without any Libraries, just plain JavaScript.

Array.prototype.sort.call(
document.getElementById('your-select').options,
function(a,b){return a.text < b.text ? -1 : a.text > b.text ? 1 : 0;}
);
You are on page 1 of 2, other pages: [1] 2

 

 

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.
 
It seems that you are
from Washington, US .

Info/ Feedback on this

Show city and country
Show country only
Hide my location
Leave your comment here:
Please type in the code:
photo Add a picture:

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.