DelphiFAQ Home Search:
General :: Programming :: JavaScript
Code snippets to add functionality to your HTML pages, preferably cross-browser.


This list is sorted by recent document popularity (not total page views).
New documents will first appear at the bottom.

Featured Article

Sorting a SELECT listbox in Javascript


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


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;
 for(i=0; i<lb.length; i++)  {
   lb.options[i].text = arrTexts[i];
   lb.options[i].value = arrTexts[i];
 <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
 <a href="javascript:sortlist()">sort</a>

Generated 8:01:33 on Aug 13, 2020