Adding Options to a Using jQuery?

Adding Options to a 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>');
2

31 Answers

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 
    }));
});
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");
$("#selectList").append(o);
0

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

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

Option 1-

You can try this-

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

Like this-

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

<select id='mySelect'></select>
James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.