How to change options of <select> with jQuery?

JqueryHtml Select

Jquery Problem Overview


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

Jquery Solutions


Solution 1 - Jquery

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 

Solution 2 - Jquery

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

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

    this.empty();
    self = this;

    $.each(options, function(index, option) {
      $option = $("<option></option>")
        .attr("value", option.value)
        .text(option.text);
      self.append($option);
    });
  };
})(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}
];

$("#foo").replaceOptions(options);

Solution 3 - Jquery

$('#comboBx').append($("<option></option>").attr("value",key).text(value));

where comboBx is your combo box id.

or you can append options as string to the already existing innerHTML and then assign to the select innerHTML.

Edit

If you need to keep the first option and remove all other then you can use

var firstOption = $("#cmb1 option:first-child");
$("#cmb1").empty().append(firstOption);

Solution 4 - Jquery

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) {
    $el.append($("<option></option>")
    .attr("value", value).text(key));
});

Solution 5 - Jquery

Removing and adding DOM element is slower than modification of existing one.

If your option sets have same length, you may do something like this:

$('#my-select option')
.each(function(index) {
    $(this).text('someNewText').val('someNewValue');
});

In case your new option set has different length, you may delete/add empty options you really need, using some technique described above.

Solution 6 - Jquery

Does this help?

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

Solution 7 - Jquery

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");
$("#selectId").html(option);

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

Solution 8 - Jquery

Old school of doing things by hand has always been good for me.

  1. Clean the select and leave the first option:

         $('#your_select_id').find('option').remove()
         .end().append('<option value="0">Selec...</option>')
         .val('whatever');
    
  2. If your data comes from a Json or whatever (just Concat the data):

         var JSONObject = JSON.parse(data);
         newOptionsSelect = '';
         for (var key in JSONObject) {
             if (JSONObject.hasOwnProperty(key)) {
                 var newOptionsSelect = newOptionsSelect + '<option value="'+JSONObject[key]["value"]+'">'+JSONObject[key]["text"]+'</option>';
             }
         }
    
         $('#your_select_id').append( newOptionsSelect );
    
  3. My Json Objetc:

         [{"value":1,"text":"Text 1"},{"value":2,"text":"Text 2"},{"value":3,"text":"Text 3"}]
    

This solution is ideal for working with Ajax, and answers in Json from a database.

Solution 9 - Jquery

if we update <select> constantly and we need to save previous value :

var newOptions = {
    'Option 1':'value-1',
    'Option 2':'value-2'
};

var $el = $('#select');
var prevValue = $el.val();
$el.empty();
$.each(newOptions, function(key, value) {
   $el.append($('<option></option>').attr('value', value).text(key));
   if (value === prevValue){
       $el.val(value);
   }
});
$el.trigger('change');

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMaskView Question on Stackoverflow
Solution 1 - JqueryChristian C. SalvadóView Answer on Stackoverflow
Solution 2 - JqueryktusznioView Answer on Stackoverflow
Solution 3 - JqueryrahulView Answer on Stackoverflow
Solution 4 - JqueryDracoView Answer on Stackoverflow
Solution 5 - JqueryYuri GorView Answer on Stackoverflow
Solution 6 - JqueryVierzehnView Answer on Stackoverflow
Solution 7 - JqueryBERGUIGA Mohamed AmineView Answer on Stackoverflow
Solution 8 - JqueryTotoView Answer on Stackoverflow
Solution 9 - JqueryRoman YakovivView Answer on Stackoverflow