By Mask


2009-11-26 04:14:03 8 Comments

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

9 comments

@Toto 2018-08-02 14:52:28

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.

@Fsh 2017-12-02 03:55:22

Does this help?

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

@sisve 2017-12-02 08:00:23

This question is about dynamically adding <option> to a <select>, not selecting a specific option.

@Roman Yakoviv 2017-11-01 15:42:16

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');

@CMS 2009-11-26 04:21:53

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 

@Mask 2009-11-26 04:27:29

How to remain the first option when empty()?

@Rakesh Juyal 2009-11-26 04:56:24

+1 for $('#selectId option:gt(0)').remove();

@phn 2016-11-30 14:42:56

If using bootstrap-select then add the following to refresh the select picker after replacing the options: $('#selectId').selectpicker('refresh'); $('#selectId').selectpicker('render');. Otherwise the new options will not be visible in your select list.

@Darós 2018-01-04 11:21:37

How can I check one of this options?

@rorofromfrance 2018-12-07 18:27:15

I personally find this syntax a bit cleaner for creating jQuery node $el.append($('<option/>', { value: value, text: key }));

@Developer 2019-03-07 11:54:49

Thanks guys. if you have to set selected value when we are editing the page for the default selected value we can use something like this in the loop for specific iteration we can add selected $el.append($('<option/>', { value: value, selected: 'selected', text: key }));

@Draco 2014-04-28 09:19:22

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));
});

@Yuri Gor 2016-02-08 13:41:57

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.

@BERGUIGA Mohamed Amine 2015-03-24 13:25:08

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.

@Jay Blanchard 2015-03-24 14:03:08

Why should the OP try this? Please add an explanation of what you did and why you did it that way not only for the OP but for future visitors to SO.

@ktusznio 2013-05-20 16:43:59

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);

@rahul 2009-11-26 04:16:08

$('#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);

@Mask 2009-11-26 04:20:18

You didn't remove the old options?

@rahul 2009-11-26 04:27:24

Do you want to clear the old ones o just add new options to the existing options?

@Mask 2009-11-26 04:29:30

yes,I want to clear the old ones except the first one.

Related Questions

Sponsored Content

55 Answered Questions

[SOLVED] How do I check if an element is hidden in jQuery?

61 Answered Questions

[SOLVED] How to check whether a checkbox is checked in jQuery?

23 Answered Questions

22 Answered Questions

[SOLVED] Get selected value in dropdown list using JavaScript

58 Answered Questions

[SOLVED] How do I redirect to another webpage?

24 Answered Questions

[SOLVED] Set select option 'selected', by value

31 Answered Questions

34 Answered Questions

40 Answered Questions

[SOLVED] Setting "checked" for a checkbox with jQuery?

15 Answered Questions

[SOLVED] "Thinking in AngularJS" if I have a jQuery background?

Sponsored Content