What\'s the easiest way to add an option
to a dropdown using jQuery?
Will this work?
$(\"#mySelect\").append(\'
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);
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));
});
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>'));
Based on dule's answer for appending a collection of items, a one-liner for...in will also work wonders:
let cities = {'ny':'New York','ld':'London','db':'Dubai','pk':'Beijing','tk':'Tokyo','nd':'New Delhi'};
for(let c in cities){$('#selectCity').append($('<option>',{value: c,text: cities[c]}))}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<select id="selectCity"></select>
Both object values and indexes are assigned to the options. This solution works even in the old jQuery (v1.4)!
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>
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
}));
});