DelphiFAQ Home Search:

Sorting a SELECT listbox in Javascript

 

comments41 comments. Current rating: 5 stars (20 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 3, other pages: [1] 2 3
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-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-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, 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;}
);
2007-04-06, 05:04:15   (updated: 2007-04-06, 05:11:21)
nodeny@gmail.com,-,SERES,Thomas from Le Kremlin-Bictre in Ile-de-France, France  
rating
Hye !
This is my version, i've simplified the code by using only one array.
Why do you think about this ?

function sortList() {
var selectBox = document.getElementById('selectBoxId');
selectArray = new Array();

for (i = 0; i < selectBox.length; i++) {
selectArray[i] = new Array();
selectArray[i][0] = selectBox.options[i].text;
selectArray[i][1] = selectBox.options[i].value;
}

selectArray.sort();

for (j = 0; j < selectBox.length; j++) {
selectBox.options[j].text = selectArray[j][0];
selectBox.options[j].value = selectArray[j][1];
}
}

and if you want to keep your first option in the select List you can use this :

function sortList() {
var selectBox = document.getElementById('selectBoxId');
selectArray = new Array();

for (i = 1; i < selectBox.length; i++) {
selectArray[i] = new Array();
selectArray[i][0] = selectBox.options[i].text;
selectArray[i][1] = selectBox.options[i].value;
}

selectArray.sort();

for (j = 0; j < selectBox.length - 1; j++) {
selectBox.options[j+1].text = selectArray[j][0];
selectBox.options[j+1].value = selectArray[j][1];
}
}
2007-05-12, 03:52:28   (updated: 2007-05-12, 03:53:00)
anonymous from India  
Hye !
This is my version.
This function sort the Numeric as well as String seperately.

function sortList(listID)
{
    var isNumeric=false;
    var selectBox = document.getElementById(listID);
    var selectArray = new Array();    
    try
    {
        for (i = 0; i < selectBox.length; i++)
        {
            selectArray[i] = new Array();
            selectArray[i][0] = selectBox.options[i].text;
            selectArray[i][1] = selectBox.options[i].value;
            isNumeric=(!isNumeric?!isNaN((selectBox.options[i].text*1)):isNumeric)
        }
        if (isNumeric)
        {
            for (i = 0; i < selectBox.length-1; i++)
            {
                for (j=i; j < selectBox.length; j++)
                {
                    if( (selectBox.options[i].text*1)>(selectBox.options[j].text*1))
                    {
                        tNum=selectBox.options[i].text;
                        tVal=selectBox.options[i].Value;
                        selectBox.options[i].text=selectBox.options[j].text
                        selectBox.options[i].Value=selectBox.options[j].value
                        selectBox.options[j].text=tNum;
                        selectBox.options[j].value=tVal;
                    }
                }
            }
        }
        else
        {
            selectArray.sort();
            for (j = 0; j < selectBox.length; j++)
            {
                selectBox.options[j].text = selectArray[j][0];
                selectBox.options[j].value = selectArray[j][1];
            }
        }
    }
    catch(e)
    {
        //In case of any error, dont do anything.
        alert('The following error occurred: ' + e.name + ' - ' + e.message);
    }
}

Regards,
Zak
2007-05-12, 04:23:45
jaggariah@rediffmail.com from Madras, India  
rating
Hi All
The following code is very usefull for sorting the list box numbers seperately and string seperately.


function sortList(listID)
{
    var selectBox = document.getElementById(listID);
    var strArray = new Array();
    var numArray = new Array();
    try
    {
        strIndex=0;
        numIndex=0;
        for (i = 0; i < selectBox.length; i++)
        {
            if (isNaN((selectBox.options[i].text*1)))
            {
                strArray[strIndex] = new Array();
                strArray[strIndex][0] = selectBox.options[i].text;
                strArray[strIndex++][1] = selectBox.options[i].value;
            }
            else
            {
                numArray[numIndex] = new Array();
                numArray[numIndex][0] = selectBox.options[i].text;
                numArray[numIndex++][1] = selectBox.options[i].value;
            }
        }
        for (i=0; i<numIndex-1; i++)
        {
            for (j=i; j<numIndex; j++)
            {
                if( (numArray[i][0]*1)>(numArray[j][0]*1))
                {
                    tNum=numArray[i][0];
                    tVal=numArray[i][1];
                    numArray[i][0]=numArray[j][0];
                    numArray[i][1]=numArray[j][1];
                    numArray[j][0]=tNum;
                    numArray[j][1]=tVal;
                }
            }
        }
        strArray.sort();
        listLength=0;
        for (j = 0; j < numIndex; j++)
        {
            selectBox.options[listLength].text = numArray[j][0];
            selectBox.options[listLength++].value = numArray[j][1];
        }
        for (j = 0; j < strIndex; j++)
        {
            selectBox.options[listLength].text = strArray[j][0];
            selectBox.options[listLength++].value = strArray[j][1];
        }
    }
    catch(e)
    {
        //In case of any error, dont do anything.
        alert('The following error occurred: ' + e.name + ' - ' + e.message);
    }
}

Regards,
Zak
+91 98414 03325


Keywords: group of indian people
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);


You are on page 1 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: