2009-05-18 2 views
1

Diese Frage ist ähnlich wie diese How do I add options to a DropDownList using jQuery? aber ich möchte es in einer geordneten Weise hinzufügen. Das Beispiel in der anderen Frage fügt es nur am Ende der Liste hinzu. Der Code lautet wie folgt:Wie füge ich Optionen zu einer DropDownList mit jQuery (geordnet) hinzu?

var myOptions = { 
     1: "Test" 
     2: "Another" 
}; 
$.each(myOptions, function(val, text) { 
     $('#Projects').append(
      $('<option></option').val(val).html(text) 
    ); 
}); 

Angenommen, die Liste bereits drei Elemente enthält: "Blah", "Foo" und "Zebra". Ich würde gerne in der Lage sein, die beiden neuen Optionen ("Test" und "Another") zu dem Dropdown-Menü hinzuzufügen, so dass es geordnet ist ("Another", "Blah", "Foo", "Test" und "Zebra") jQuery.

Jede Hilfe wird sehr geschätzt !!!

Antwort

1

Geben dieses gehen:

// Sort Function 
function sortAlpha(a,b) { 
    if(a.name > b.name) { 
     return 1; 
    } else if(a.name < b.name) { 
     return -1; 
    } 
    return 0; 
} 


// Options you want to add 
var myOptions = [ {id:1, name:"Test"}, {id:2, name:"Another" } ]; 

// Create array from existing options and merge 
$.merge(myOptions, 
    $.map($('#Projects').find('option'), function(n){ 
     return { id:n.value, name:n.innerHTML}; 
    }) 
); 

// Sort all options using above sort function 
myOptions.sort(sortAlpha); 

// Clear the <select> of existing options 
$('#Projects').empty(); 

// Add the options to the <select> 
$.each(myOptions, function() { 
     $('#Projects').append(
      $('<option></option').val(this.id).html(this.name) 
    ); 
}); 
1

Werfen Sie einen Blick auf die jQuery bezogene Antwort here. Sie müssen natürlich Ihre neuen Optionen hinzufügen, bevor Sie die Sortiermethode aufrufen.

Verwandte Themen