Adding options to a using jQuery?

What’s the easiest way to add an option to a dropdown using jQuery?
Will this work?


Solution 1:

This did NOT work in IE8 (yet did in FF):

$("#selectList").append(new Option("option text", "value"));

This DID work:

var o = new Option("option text", "value");
/// jquerify the DOM object 'o' so we can use the html method
$(o).html("option text");

Solution 2:

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 

Solution 3:

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

Solution 4:

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

Solution 5:

Option 1-

You can try this-

    value: value_variable,
    text : text_variable

Like this-

for (i = 0; i < 10; i++)
        value: i,
        text : "Option "+i 
<script src=""></script>

<select id='mySelect'></select>

Option 2-

Or try this-

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

Like this-

for (i = 0; i < 10; i++)
     $('#mySelect').append( '<option value="'+i+'">'+'Option '+i+'</option>' );
<script src=""></script>

<select id='mySelect'></select>

Solution 6:

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.

Related:  node.js async.series is that how it is supposed to work?