michael: Select Options sortieren

Beitrag lesen

Hallo,

ich will eine bestehende Option-Liste via JS um eine Option erweitern. Die Liste soll aber alphabethisch sortiert bleiben. Hierfür lese ich mir die Liste in ein Array, lösche die Liste, sortiere das Array und schreibe es zurück in die Liste. Das funktioniert auch ganz gut.

Das Problem ist aber das sortieren! Das scheint partou nicht zu klappen ;(

Weiss jemand warum?
Hier mein Code:

addOption(document.GetElementById("meinSelect"), "opt", "1");

function addOption(target, option, value) {
    var opts = new Array();

while(target.length){
        var oldopt = new Array();
        oldopt["value"] = target.options[0].value;
        oldopt["text"] = target.options[0].text;
        opts.push(oldopt);
        target.remove(0);
    }

var newopt = new Array();
    newopt["value"] = value;
    newopt["text"] = text;
    opts.push(newopt);

opts.sort(sortByOptionText);

for(var i=0; i<opts.length; i++){
        target.options.add(new Option(opts[i]["text"], opts[i]["value"], false, false));
    }
}

function sortByOptionText(a, b) {
    var x = a["text"];
    var y = b["text"];
    return (x < y);
}