Coder Perfect

What’s the best approach to use jQuery to add choices to a select from a JavaScript object?


What is the best way to use jQuery to add choices to a select from a JavaScript object?

I’m seeking for something that doesn’t require the use of a plugin, but I’m also curious about the plugins that are available.

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 reduced and cleaned-up version of matdumsa’s:

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

Changes from matdumsa’s version: (1) the closing tag for the option inside append() was deleted, and (2) the properties/attributes were relocated to a map as the second parameter of append() ().

Asked by Darryl Hein

Solution #1

In a jQuery-like approach, the same as the other answers:

$.each(selectValues, function(key, value) {   
                    .attr("value", key)

Answered by matdumsa

Solution #2

var output = [];

$.each(selectValues, function(key, value)
  output.push('<option value="'+ key +'">'+ value +'</option>');


This manner, you just “touch the DOM” once.

Because I’m not familiar with jQuery internals (maybe it does some processing in the html() function), I’m not sure if the last line can be transformed to $(‘#mySelect’).html(output.join(“)).

Answered by gpilotino

Solution #3

This is slightly faster and cleaner.

Answered by ajevic

Solution #4

var list = $("#selectList");
$.each(items, function(index, item) {
  list.append(new Option(item.text, item.value));
var list = document.getElementById("selectList");
for(var i in items) {
  list.add(new Option(items[i].text, items[i].value));

Answered by Carl Hörberg

Solution #5

If you don’t need to support older versions of Internet Explorer, the Option constructor is clearly the way to go, as it is both readable and efficient:

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

It’s functionally equivalent to, but cleaner than:

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

Answered by Nickolay

Post is based on