1

This question is similar to this one 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!!!

2 Answers 2

1

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)
      );
});
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.