What is the best way to add options to a select from a JavaScript object with jQuery?

Viewed 1095120

What is the best method for adding options to a <select> from a JavaScript object using jQuery?

I'm looking for something that I don't need a plugin to do, but I would also be interested in the plugins that are out there.

This is what I did:

selectValues = { "1": "test 1", "2": "test 2" };

for (key in selectValues) {
  if (typeof (selectValues[key] == 'string') {
    $('#mySelect').append('<option value="' + key + '">' + selectValues[key] + '</option>');
  }
}

A clean/simple solution:

This is a cleaned up and simplified version of matdumsa's:

$.each(selectValues, function(key, value) {
     $('#mySelect')
          .append($('<option>', { value : key })
          .text(value));
});

Changes from matdumsa's: (1) removed the close tag for the option inside append() and (2) moved the properties/attributes into an map as the second parameter of append().

37 Answers

The same as other answers, in a jQuery fashion:

$.each(selectValues, function(key, value) {   
     $('#mySelect')
         .append($("<option></option>")
                    .attr("value", key)
                    .text(value)); 
});

If you don't have to support old IE versions, using the Option constructor is clearly the way to go, a readable and efficient solution:

$(new Option('myText', 'val')).appendTo('#mySelect');

It's equivalent in functionality to, but cleaner than:

$("<option></option>").attr("value", "val").text("myText")).appendTo('#mySelect');

This looks nicer, provides readability, but is slower than other methods.

$.each(selectData, function(i, option)
{
    $("<option/>").val(option.id).text(option.title).appendTo("#selectBox");
});

If you want speed, the fastest (tested!) way is this, using array, not string concatenation, and using only one append call.

auxArr = [];
$.each(selectData, function(i, option)
{
    auxArr[i] = "<option value='" + option.id + "'>" + option.title + "</option>";
});

$('#selectBox').append(auxArr.join(''));

I have made something like this, loading a dropdown item via Ajax. The response above is also acceptable, but it is always good to have as little DOM modification as as possible for better performance.

So rather than add each item inside a loop it is better to collect items within a loop and append it once it's completed.

$(data).each(function(){
    ... Collect items
})

Append it,

$('#select_id').append(items); 

or even better

$('#select_id').html(items);
function populateDropdown(select, data) {   
    select.html('');   
    $.each(data, function(id, option) {   
        select.append($('<option></option>').val(option.value).html(option.name));   
    });          
}   

It works well with jQuery 1.4.1.

For complete article for using dynamic lists with ASP.NET MVC & jQuery visit:

Dynamic Select Lists with MVC and jQuery

$.each(selectValues, function(key, value) {
    $('#mySelect').append($("<option/>", {
        value: key, text: value
    }));
});

Actually, for getting the improved performance, it's better to make option list separately and append to select id.

var options = [];
$.each(selectValues, function(key, value) {
    options.push ($('<option>', { value : key })
          .text(value));
});
 $('#mySelect').append(options);

http://learn.jquery.com/performance/append-outside-loop/

I decided to chime in a bit.

  1. Deal with prior selected option; some browsers mess up when we append
  2. ONLY hit DOM once with the append
  3. Deal with multiple property while adding more options
  4. Show how to use an object
  5. Show how to map using an array of objects

// objects as value/desc
let selectValues = {
  "1": "test 1",
  "2": "test 2",
  "3": "test 3",
  "4": "test Four"
};
//use div here as using "select" mucks up the original selected value in "mySelect"
let opts = $("<div />");
let opt = {};
$.each(selectValues, function(value, desc) {
  opts.append($('<option />').prop("value", value).text(desc));
});
opts.find("option").appendTo('#mySelect');

// array of objects called "options" in an object
let selectValuesNew = {
  options: [{
      value: "1",
      description: "2test 1"
    },
    {
      value: "2",
      description: "2test 2",
      selected: true
    },
    {
      value: "3",
      description: "2test 3"
    },
    {
      value: "4",
      description: "2test Four"
    }
  ]
};

//use div here as using "select" mucks up the original selected value
let opts2 = $("<div />");
let opt2 = {}; //only append after adding all options
$.map(selectValuesNew.options, function(val, index) {
  opts2.append($('<option />')
    .prop("value", val.value)
    .prop("selected", val.selected)
    .text(val.description));
});
opts2.find("option").appendTo('#mySelectNew');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="mySelect">
  <option value="" selected="selected">empty</option>
</select>

<select id="mySelectNew" multiple="multiple">
  <option value="" selected="selected">2empty</option>
</select>

Since JQuery's append can take an array as an argument, I'm surprised nobody suggested making this a one-liner with map

$('#the_select').append(['a','b','c'].map(x => $('<option>').text(x)));

or reduce

['a','b','c'].reduce((s,x) => s.append($('<option>').text(x)), $('#the_select'));

Getting the object keys to get the object values. Using map() to add new Options.

const selectValues = {
  "1": "test 1",
  "2": "test 2"
}
const selectTest = document.getElementById('selectTest')
Object.keys(selectValues).map(key => selectTest.add(new Option(selectValues[key], key)))
<select id="selectTest"></select>

Pure JS

In pure JS adding next option to select is easier and more direct

mySelect.innerHTML+= `<option value="${key}">${value}</option>`;

let selectValues = { "1": "test 1", "2": "test 2" };

for(let key in selectValues) { 
  mySelect.innerHTML+= `<option value="${key}">${selectValues[key]}</option>`;
}
<select id="mySelect">
  <option value="0" selected="selected">test 0</option>
</select>

 $.each(response, function (index,value) {
                        $('#unit')
                            .append($("<option></option>")
                                .attr("value", value.id)
                                .text(value.title));
                    });
Related