Saturday, December 29, 2007

JavaScript: Alphabetically sort a HTML list control

// ***
// Sort a HTML list control
// ***
function sortList(lst)
{
if (lst==null)
return;

arrList = new Array();
for(i=0; i < lst.length; i++)
{
arrList[i] = lst.options[i].text;
}
arrList.sort();
for(i=0; i < lst.length; i++)
{
lst.options[i].text = arrList[i];
lst.options[i].value = arrList[i];
}
}

4 comments:

  1. Ok I dont think this is what im looking for but, you might know how to do what I ma looking for.

    I need to write (in HTML format) a phone list but i want the phone list to auto sort from "A" - "Z" (so when i get new numbers i dont have to manually find the correct location for this person)

    Any idea on how to do this?

    ReplyDelete
  2. Here's a related function to sort an HTML list or element with child nodes (ul, ol, dl, div, etc.) that uses the same idea:

    function sortList(listId)
    {
    var ul = document.getElementById(listId);
    arrList = new Array();
    j = 0;
    for (i=0; i<ul.childNodes.length; i++) {
    if (ul.childNodes[i].innerHTML == undefined) continue;
    arrList[j] = ul.childNodes[i].innerHTML;
    j++;
    }
    j = 0;
    arrList.sort();
    for (i=0; i<ul.childNodes.length; i++) {
    if (ul.childNodes[i].innerHTML == undefined) continue;
    ul.childNodes[i].innerHTML = arrList[j];
    j++;
    }
    }

    ReplyDelete
  3. can this be written in css format as well?

    ReplyDelete

Please use your common sense before making a comment, and I truly appreciate your constructive criticisms.