views:

742

answers:

2

This question is similar to this one http://stackoverflow.com/questions/317095/how-do-i-add-options-to-a-dropdownlist-using-jquery but I would like to add it in an ordered fashion. The example in the other question just adds it to the end of the list. The code is as follows:

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

Suppose the list already contains 3 items: "Blah", "Foo" and "Zebra". I'd like to be able to add the two new options ("Test" and "Another") to the dropdown so it's ordered ("Another", "Blah", "Foo", "Test" and "Zebra") using jQuery.

Any help is much appreciated!!!

+1  A: 

Take a look at the jQuery related answer here. You would, of course, need to add your new options before calling the sort method.

Jab
+1  A: 

Give this a go:

// 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)
      );
});
Scott McMillin