What is the best way to add options to a select from an array with jQuery?

What is the best way to add options to a select from an array with jQuery?

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

I’m looking for something that I don’t need a plugin to do, but 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().

what is best way to get select options, values from js array

I’m trying to write js so that my select option dropdown gets the value and text from my array. js is new for me. jsfiddle I need the value to be the number and text the text in quotes from: var locat

dynamically building select statement from DOM data element [duplicate]

This question already has an answer here: What is the best way to add options to a select from an array with jQuery? 25 answers I need to dynamically build a select dropdown based on form data

jquery / php select multiple selected options from php array in jquery

I’m trying to produce a multiple select list with selected options based from a php array, in jquery. I can’t seem to get it working, this is my code: My select list: <select name=modules[] id=m

Trying to dynamically add options to an array of HTML select fields Php/AJAX/jQuery

I have an HTML array of 10 select fields that must be populated by jQuery each time the div-popup is called. (Each one gets the same options) We have periodic needs for hundreds of employees and this

Generate select options from array and select multiple element by comparing with another array (jQuery)

What I want to do is to generate option elements for a multiple select drop-down from a JavaScript array. Than select each option in the drop-down that is the same as the value in another array (The r

What is the best way to send PHP array via jquery?

can anybody help to explain or give reference on how to send array of multiple array (or just array ) in jquery. and what the best way to do when something is failed or successfull. what i mean is how

What is the best way to add array into Mysql

I am making a simple order form with 5 products and they can be select with a checkbox from the user and then I want to add the products that the visitors will select into mysql database, but as you k

What’s the best way to add jQuery enhancements to a website?

For a while now, I’m been using jQuery to offer enhancements via JavaScript on my websites. However, I’m now beginning to ponder—from a performance point of view—what is the best way to organise my fi

What is the best way to select a random vertex from Titan graph database

I need to select random vertex or edge from a graph. I am currently using blueprints API to query graph. What is the best way to randomly pick a vertex or an edge from my graph?

What is the best way to return single object instead of array from jQuery selection?

Newb question: jQuery(‘.foo’)[0] does the job most of the time. jQuery(‘.foo:first’)[0] is slightly more explicit and performant. But this isn’t nice when array is empty, so check is necessary. But is

Answers

Same as other answers, in jQuery fashion:

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

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

Using DOM Elements Creator plugin (my favorite):

$.create('option', {'value': 'val'}, 'myText').appendTo('#mySelect');

Using the Option constructor (not sure about browser support):

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

Using document.createElement (avoiding extra work parsing HTML with $(“<option></option>”)):

$('#mySelect').append($(document.createElement("option")).
                        attr("value","val").text("myText"));
var output = [];

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

$('#mySelect').html(output.join(''));

In this way you “touch the DOM” only one time.


I’m not sure if the latest line can be converted into $(‘#mySelect’).html(output.join(”)) because I don’t know jquery internals (maybe it does some parsing in the html() method)

 var output = [];
 var length = data.length;
 for(var i=0; i < length; i++)
 {
    output[i++] = '<option value="'+ data[i].start +'">'+ data[i].start +'</option>';
 }

 $('#choose_schedule').get(0).innerHTML = output.join('');

I’ve done a few tests and this is, I believe does the job the fastest 😛

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(''));
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: http://www.codecapers.com/post/Dynamic-Select-Lists-with-MVC-and-jQuery.aspx

simple way is

$('#SelectId').html("<option value='0'>select </option><option value='1'>Laguna</option>");

This is slightly faster and cleaner.

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

There’s an approach using the Microsoft Templating approach that’s currently under proposal for inclusion into jQuery core. There’s more power in using the templating so for the simplest scenario it may not be the best option. For more details see Scott Gu’s post outlining the features.

First include the templating js file, available from github.

<script src="Scripts/jquery.tmpl.js" type="text/javascript" />

Next set-up a template

<script id="templateOptionItem" type="text/html">
    <option value=/'{{= Value}}/'>{{= Text}}</option>
</script>

Then with your data call the .render() method

var someData = [
    { Text: "one", Value: "1" },
    { Text: "two", Value: "2" },
    { Text: "three", Value: "3"}];

$("#templateOptionItem").render(someData).appendTo("#mySelect");

I’ve blogged this approach in more detail.

You can just iterate over your json array with the following code

$(‘<option/>’).attr(“value”,”someValue”).text(“Option1”).appendTo(“#my-select-id”);

A compromise of sorts between the top two answers, in a “one-liner”:

$.fn.append.apply($('mySelect'),
    $.map(selectValues, function(val, idx) {
        return $("<option/>")
            .val(val.key)
            .text(val.value);
    })
);

Builds up an array of Option elements using map and then appends them all to the Select at once by using apply to send each Option as a separate argument on the append function.

jQuery

var list = $("#selectList");
$.each(items, function(index, item) {
  list.append(new Option(item.text, item.value));
});

pure javascript

var list = document.getElementById("selectList");
for(var i in items) {
  list.add(new Option(items[i].text, items[i].value));
}

Be forwarned… I am using jQuery Mobile 1.0b2 with PhoneGap 1.0.0 on an Android 2.2 (Cyanogen 7.0.1) phone (T-Mobile G2) and could not get the .append() method to work at all. I had to use .html() like follows:

var options;
$.each(data, function(index, object) {
    options += '<option value="' + object.id + '">' + object.stop + '</option>';
});

$('#selectMenu').html(options);

I found that this is simple and works great.

for (var i = 0; i < array.length; i++) {
    $('#clientsList').append($("<option></option>").text(array[i].ClientName).val(array[i].ID));
};

that’s what i did with two-dimensional array: first column is item i add to innerHTML of the <option>, second column is record_id i add to the value of the <option>:

  1. PHP

    $items = $dal->get_new_items(); //gets data from the db
    $items_arr = array();
    $i = 0;
    foreach ($items as $item)
    {
        $first_name = $item->first_name;
        $last_name = $item->last_name;
        $date = $item->date;
        $show = $first_name . " " . $last_name . ", " . $date;
        $request_id = $request->request_id;
        $items_arr[0][$i] = $show;
        $items_arr[1][$i] = $request_id;
        $i++;
        }
    
        echo json_encode($items_arr);
    
  2. JS/AJAX

    function ddl_items(){
    if (window.XMLHttpRequest){
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else{
        // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    
    xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
        var arr = JSON.parse(xmlhttp.responseText);
        var lstbx = document.getElementById('my_listbox');
    
        for (var i=0; i<arr.length; i++) {
                var option = new Option(arr[0][i], arr[1][i]);
                lstbx.options.add(option);
            }
        }
    };
    
        xmlhttp.open("GET","Code/get_items.php?dummy_time="+new Date().getTime()+"",true);
        xmlhttp.send();
        }
       }
    

There’s a sorting problem with this solution in Chrome (jQuery 1.7.1) (Chrome sorts object properties by name/number?) So to keep the order (yes, it’s object abusing), I changed this:

optionValues0 = {"4321": "option 1", "1234": "option 2"};

to this

optionValues0 = {"1": {id: "4321", value: "option 1"}, "2": {id: "1234", value: "option 2"}};

and then the $.each will look like:

$.each(optionValues0, function(order, object) {
  key = object.id;
  value = object.value;
  $('#mySelect').append($('<option>', { value : key }).text(value));
}); 

Although the above are all valid answers – it might be advisable to append all these to a documentFragmnet first, then append that document fragment as an elemet after…

see John Resig’s thoughts on the matter..

Something along the lines of:

var frag = document.createDocumentFragment();

for(item in data.Events)
{
   var option = document.createElement("option");

   option.setAttribute("value", data.Events[item].Key);
   option.innerText = data.Events[item].Value;

   frag.appendChild(option);
}
eventDrop.empty();
eventDrop.append(frag);

@joshperry

It seems that plain .append also works as expected,

$("mySelect").append(
  $.map(selectValues, function(v,k){

    return $("<option>").val(k).text(v);
  })
);

Yet another way of doing it:

var options = [];    
$.each(selectValues, function(key, value) {
    options.push($("<option/>", {
        value: key,
        text: value
    }));
});
$('#mySelect').append(options);
if (data.length != 0) {
    var opts = "";
    for (i in data)
        opts += "<option value='"+data[i][value]+"'>"+data[i][text]+"</option>";

    $("#myselect").empty().append(opts);
}

This manipulates the DOM only once after first building a giant string.

All of these answers seem unnecessarily complicated. All you need is:

var options = $('#mySelect').get(0).options;
$.each(selectValues, function(key, value) {
        options[options.length] = new Option(key, value);
});

That is completely cross browser compatible.

  1. $.each is slower then for loop
  2. Each time dom selection is not best practice in loop $(“#mySelect”).append();

So best solution is following

if json data resp is

    [
        {"id":"0001","name":"Mr. P"},
        {"id":"0003","name":"Mr. Q"},
        {"id":"0054","name":"Mr. R"},
        {"id":"0061","name":"Mr. S"}
    ]

use it as

    var option = "";
    for (i=0; i<resp.length; i++) {
        option += "<option value='"+resp[i].emp_id+"'>"+resp[i].name+"</option>";
    }
    $('#mySelect').html(option);

I combine the two best answers into a great answer.

var outputConcatenation = [];

$.each(selectValues, function(i, item) {   
     outputConcatenation.push($("<option></option>").attr("value", item.key).attr("data-customdata", item.customdata).text(item.text).prop("outerHTML"));
});

$("#myselect").html(outputConcatenation.join(''));

Rather than repeating the same code everywhere, I would suggest it is more desirable to write your own JQuery function like:

jQuery.fn.addOption = function (key, value) {
    $(this).append($('<option>', { value: key }).text(value));
};

Then to add an option just do the following:

$('select').addOption('0', 'None');

The JSON Format:

[{
    "org_name": "Asset Management"
}, {
    "org_name": "Debt Equity Foreign services"
}, {
    "org_name": "Credit Services"
}]

And the Jquery to populate the values to the Dropdown on ajax success:

success: function(json) {
var options = [];
$('#org_category').html('');  // Set the Dropdown as Blank before new Data
options.push('<option>-- Select Category --</option>');
$.each(JSON.parse(json), function(i, item) {
       options.push($('<option/>', 
       {
          value: item.org_name, text: item.org_name 
       }));
    });
 $('#org_category').append(options);  // Set the Values to Dropdown
}

Using the $.map() function, you can do this in a more elegant way :

$('#mySelect').html( $.map(selectValues, function(val, key){
     return '<option value="' + val + '">'+ key + '</option>';
}).join('') );