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

How to insert a string into a sorted SELECT listbox


I have a sorted listbox and want to insert a new string without a complete resort.


Use the javascript function shown below - pass the string that you want to insert as an argument. The name of the SELECT listbox is hard-coded in the script as 'mylist'.

Call it like this:
insertSortedLb('New Name')

The case is case sensitive and sorts alphabetically.
That means if you have numbers in the listbox, and these numbers include
10, 2, 300
then it will sort these numbers as
10, 2, 300
NOT as
2, 10, 300

function insertSortedLb(sVal) {
 var lb = document.getElementById('mylist');
 oOption = document.createElement("OPTION");
 oOption.text = '';
 oOption.value = '';
 oOption.selected = false;
 lb.options[lb.length] = oOption;
 for(i=lb.length-1; i>0; i--)  {
   if (lb.options[i-1].text < sVal) {
     oOption = document.createElement("OPTION");
     oOption.text = sVal;
     oOption.value = sVal;
     oOption.selected = false;
     lb.options[i] = oOption;
   else {
     lb.options[i].text = lb.options[i-1].text;
     lb.options[i].value = lb.options[i-1].value;
 } // for
} // end of insertSortedLb()

Generated 8:01:31 on May 25, 2020