How to change options of <select> with jQuery?

html-select, jquery

Solution

You can remove the existing options by using the `empty` method, and then add your new options:

var option = $('<option></option>').attr("value", "option value").text("Text");
$("#selectId").empty().append(option);

If you have your new options in an object you can:

var newOptions = {"Option 1": "value1",
  "Option 2": "value2",
  "Option 3": "value3"
};

var $el = $("#selectId");
$el.empty(); // remove old options
$.each(newOptions, function(key,value) {
  $el.append($("<option></option>")
     .attr("value", value).text(key));
});

Edit: For removing the all the options but the first, you can use the `:gt` selector, to get all the `option` elements with index greater than zero and `remove` them:

$('#selectId option:gt(0)').remove(); // remove all options, but not the first 

Problem

Suppose a list of options is available, how do you update the `<select>` with new `<option>`s?

Original source