What\'s the easiest way to add an option
to a dropdown using jQuery?
Will this work?
$(\"#mySelect\").append(\'
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);
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="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id='mySelect'></select>
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="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id='mySelect'></select>
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);
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.
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'));
You can do this in ES6:
$.each(json, (i, val) => {
$('.js-country-of-birth').append(`<option value="${val.country_code}"> ${val.country} </option>`);
});