[javascript] Adding options to a <select> using jQuery?

What's the easiest way to add an option to a dropdown using jQuery?

Will this work?

$("#mySelect").append('<option value=1>My option</option>');

This question is related to javascript jquery html-select

The answer is


You can add options dynamically into dropdown as shown in below example. Here in this example I have taken array data and binded those array value to dropdown as shown in output screenshot

Output:

enter image description here

_x000D_
_x000D_
var resultData=["Mumbai","Delhi","Chennai","Goa"]_x000D_
$(document).ready(function(){_x000D_
   var myselect = $('<select>');_x000D_
     $.each(resultData, function(index, key) {_x000D_
      myselect.append( $('<option></option>').val(key).html(key) );_x000D_
       });_x000D_
      $('#selectCity').append(myselect.html());_x000D_
});
_x000D_
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js">_x000D_
</script>_x000D_
_x000D_
<select  id="selectCity">_x000D_
_x000D_
</select>
_x000D_
_x000D_
_x000D_


If someone comes here looking for a way to add options with data properties

Using attr

var option = $('<option>', { value: 'the_value', text: 'some text' }).attr('family', model.family);

Using data - version added 1.2.3

var option = $('<option>', { value: 'the_value', text: 'some text' }).data('misc', 'misc-value);

$('#select_id').append($('<option>',{ value: v, text: t }));

Try

mySelect.innerHTML+= '<option value=1>My option</option>';

_x000D_
_x000D_
btn.onclick= _=> mySelect.innerHTML+= `<option selected>${+new Date}</option>`
_x000D_
<button id="btn">Add option</button>

<select id="mySelect"></select>
_x000D_
_x000D_
_x000D_


To help performance you should try to only alter the DOM once, even more so if you are adding many options.

var html = '';

for (var i = 0, len = data.length; i < len; ++i) {
    html.join('<option value="' + data[i]['value'] + '">' + data[i]['label'] + '</option>');
}           

$('#select').append(html);

If you want to insert the new option at a specific index in the select:

$("#my_select option").eq(2).before($('<option>', {
    value: 'New Item',
    text: 'New Item'
}));

This will insert the "New Item" as the 3rd item in the select.


U can try below code to append to option

  <select id="mySelect"></select>

    <script>
          $("#mySelect").append($("<option></option>").val("1").html("My enter code hereoption"));
    </script>

You can do this in ES6:

$.each(json, (i, val) => {
    $('.js-country-of-birth').append(`<option value="${val.country_code}"> ${val.country} </option>`);
  });

for whatever reason doing $("#myselect").append(new Option("text", "text")); isn't working for me in IE7+

I had to use $("#myselect").html("<option value='text'>text</option>");


We found some problem when you append option and use jquery validate. You must click one item in select multiple list. You will add this code to handle:

$("#phonelist").append("<option value='"+ 'yournewvalue' +"' >"+ 'yournewvalue' +"</option>");

$("#phonelist option:selected").removeAttr("selected"); // add to remove lase selected

$('#phonelist option[value=' + 'yournewvalue' + ']').attr('selected', true); //add new selected

https://i.stack.imgur.com/HOjIY.png


This is just a quick points for best performance

always when you are dealing with many options, build a big string and then add it to the 'select' for best performance

f.g.

var $mySelect = $('#mySelect'); var str = '';

$.each(items, function (i, item) {
    // IMPORTANT: no selectors inside the loop (for the best performance)
    str += "<option value='" + item.value + "'> " + item.text + "</option>";
});
// you built a big string

$mySelect.html(str); // <-- here you add the big string with a lot of options into the selector.
$mySelect.multiSelect('refresh');

Even faster

var str = ""; 
for(var i; i = 0; i < arr.length; i++){
    str += "<option value='" + item[i].value + "'> " + item[i].text + "</option>";
}    
$mySelect.html(str);
$mySelect.multiSelect('refresh');

That works well.

If adding more than one option element, I'd recommend performing the append once as opposed to performing an append on each element.


Personally, I prefer this syntax for appending options:

$('#mySelect').append($('<option>', {
    value: 1,
    text: 'My option'
}));

If you're adding options from a collection of items, you can do the following:

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

This is the way i did it, with a button to add each select tag.

$(document).on("click","#button",function() {
   $('#id_table_AddTransactions').append('<option></option>')
}

How about this

var numbers = [1, 2, 3, 4, 5];
var option = '';

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

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

Just by single line

   $.each(result, function (k,v) {
                         **if(k == selectedMonthNumber) var selectedMonth = 'selected'; else var selectedMonth = '';**
                             $("#periodMonth").append($('<option>', {
                                 value: k,
                                 text: v,
                                 **selected: selectedMonth**
                         }));
                    })

Why not simply?

$('<option/>')
  .val(optionVal)
  .text('some option')
  .appendTo('#mySelect')

This is very simple:

$('#select_id').append('<option value="five" selected="selected">Five</option>');

or

$('#select_id').append($('<option>', {
                    value: 1,
                    text: 'One'
                }));

$(function () {
     var option = $("<option></option>");
     option.text("Display text");
     option.val("1");
     $("#Select1").append(option);
});

If you getting data from some object, then just forward that object to function...

$(function (product) {
     var option = $("<option></option>");
     option.text(product.Name);
     option.val(product.Id);
     $("#Select1").append(option);
});

Name and Id are names of object properties...so you can call them whatever you like...And ofcourse if you have Array...you want to build custom function with for loop...and then just call that function in document ready...Cheers


You can add option using following syntax, Also you can visit to way handle option in jQuery for more details.

  1. $('#select').append($('<option>', {value:1, text:'One'}));

  2. $('#select').append('<option value="1">One</option>');

  3. var option = new Option(text, value); $('#select').append($(option));


You can append and set the Value attribute with text:

$("#id").append($('<option></option>').attr("value", '').text(''));
$("#id").append($('<option></option>').attr("value", '4').text('Financial Institutions'));

Not mentioned in any answer but useful is the case where you want that option to be also selected, you can add:

var o = new Option("option text", "value");
o.selected=true;
$("#mySelect").append(o);

Option 1-

You can try this-

$('#selectID').append($('<option>',
 {
    value: value_variable,
    text : text_variable
}));

Like this-

_x000D_
_x000D_
for (i = 0; i < 10; i++)_x000D_
{ _x000D_
     $('#mySelect').append($('<option>',_x000D_
     {_x000D_
        value: i,_x000D_
        text : "Option "+i _x000D_
    }));_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<select id='mySelect'></select>
_x000D_
_x000D_
_x000D_

Option 2-

Or try this-

$('#selectID').append( '<option value="'+value_variable+'">'+text_variable+'</option>' );

Like this-

_x000D_
_x000D_
for (i = 0; i < 10; i++)_x000D_
{ _x000D_
     $('#mySelect').append( '<option value="'+i+'">'+'Option '+i+'</option>' );_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<select id='mySelect'></select>
_x000D_
_x000D_
_x000D_


$('#mySelect').empty().append('<option value=1>My option</option>').selectmenu('refresh');

There are two ways. You can use either of these two.

First:

$('#waterTransportationFrom').append('<option value="select" selected="selected">Select From Dropdown List</option>');

Second:

$.each(dataCollecton, function(val, text) {            
    options.append($('<option></option>').val(text.route).html(text.route));
});

I like to use non jquery approach:

mySelect.add(new Option('My option', 1));

If the option name or value is dynamic, you won't want to have to worry about escaping special characters in it; in this you might prefer simple DOM methods:

var s= document.getElementById('mySelect');
s.options[s.options.length]= new Option('My option', '1');

Based on dule's answer for appending a collection of items, a one-liner for...in will also work wonders:

_x000D_
_x000D_
let cities = {'ny':'New York','ld':'London','db':'Dubai','pk':'Beijing','tk':'Tokyo','nd':'New Delhi'};_x000D_
_x000D_
for(let c in cities){$('#selectCity').append($('<option>',{value: c,text: cities[c]}))}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>_x000D_
<select  id="selectCity"></select>
_x000D_
_x000D_
_x000D_

Both object values and indexes are assigned to the options. This solution works even in the old jQuery (v1.4)!


if u have optgroup inside select, u got error in DOM.

I think a best way:

$("#select option:last").after($('<option value="1">my option</option>'));

var select = $('#myselect');
var newOptions = {
                'red' : 'Red',
                'blue' : 'Blue',
                'green' : 'Green',
                'yellow' : 'Yellow'
            };
$('option', select).remove();
$.each(newOptions, function(text, key) {
    var option = new Option(key, text);
    select.append($(option));
});

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html-select

How can I get new selection in "select" in Angular 2? How to show disable HTML select option in by default? Remove Select arrow on IE Bootstrap 3 select input form inline Change <select>'s option and trigger events with JavaScript How to use a Bootstrap 3 glyphicon in an html select Creating a select box with a search option Drop Down Menu/Text Field in one How to have a default option in Angular.js select box How to set the 'selected option' of a select dropdown list with jquery