Save your parameters in an array of objects and generate your choice from this object. Then add new elements to this array and restore your selection.
$(function() { // Any options always on the top var topOptions = '<option value=""> </option>'; // Your middle, sorted options var options = [{val: 9, text: "AAAAA"}, {val: 11, text: "BBBBB"},{val: 10, text: "G"},{val: 12, text: "Z"}]; // Any options always on the bottom var bottomOptions = '<option value="">--</option><option value="add">Add a New</option>'; // Function to populate the select options from above data function populateOptions(element, options) { // Sort options options = options.sort(function(a, b) { return a.text.toLowerCase() > b.text.toLowerCase(); }); $(element).html('').append(topOptions); for (var i = 0; i < options.length; i++) { $('<option>').attr("value", options[i].val).text(options[i].text).appendTo($(element)); } $(element).append(bottomOptions); } // Start by populating the select populateOptions('#user_department_id', options); // Add and repopulate when add requested $('#user_department_id').on('change', function() { if ($(this).val() == "add") { // Add option to list options.push({val: data.id, text: data.text}); // Repopulate select populateOptions(this, options); // Select the new item $(this).val(data.id); } }); });
Demo: http://jsfiddle.net/kfC3S/
source share