How to change options of <select> with jQuery?


I threw CMS's excellent answer into a quick jQuery extension:

(function($, window) {
  $.fn.replaceOptions = function(options) {
    var self, $option;

    self = this;

    $.each(options, function(index, option) {
      $option = $("<option></option>")
        .attr("value", option.value)
})(jQuery, window);

It expects an array of objects which contain "text" and "value" keys. So usage is as follows:

var options = [
  {text: "one", value: 1},
  {text: "two", value: 2}


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

For some odd reason this part

$el.empty(); // remove old options

from CMS solution didn't work for me, so instead of that I've simply used this

el.html(' ');

And it's works. So my working code now looks like that:

var newOptions = {
    "Option 1":"option-1",
    "Option 2":"option-2"

var $el = $('.selectClass');
$el.html(' ');
$.each(newOptions, function(key, value) {
    .attr("value", value).text(key));

If for example your html code contain this code:

<select id="selectId"><option>Test1</option><option>Test2</option></select>

In order to change the list of option inside your select, you can use this code bellow. when your name select named selectId.

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

in this example above i change the old list of option by only one new option.

Does this help?

$("#SelectName option[value='theValueOfOption']")[0].selected = true;