http://www.electrictoolbox.com/jquery-add-option-select-jquery/
Adding a single option can be done by appending HTML to the select box. The select in the above example has an id of "example" i.e. <select id="example"> and using this method adding a new option by appending HTML can look like this:
$('#example').append('<option value="foo" selected="selected">Foo</option>');
$('#example').append(new Option('Foo', 'foo', true, true));
var options = $('#example').attr('options'); options[options.length] = new Option('Foo', 'foo', true, true);
var newOptions = { 'red' : 'Red', 'blue' : 'Blue', 'green' : 'Green', 'yellow' : 'Yellow' }; var selectedOption = 'green'; var select = $('#example'); if(select.prop) { var options = select.prop('options'); } else { var options = select.attr('options'); } $('option', select).remove(); $.each(newOptions, function(val, text) { options[options.length] = new Option(text, val); }); select.val(selectedOption);
onclick="$('#example option').remove()" //清除所有選項
http://stackoverflow.com/questions/170986/what-is-the-best-way-to-add-options-to-a-select-from-an-array-with-jquery
selectValues = {"1":"test 1","2":"test 2"};
1.
for (key in selectValues) {
if (typeof(selectValues[key] == 'string') {
$('#mySelect').append('<option value="' + key + '">' + selectValues[key] + '</option>');
}
}
2.
$.each(selectValues, function(key, value) {
$('#mySelect')
.append($('<option>', { value : key })
.text(value));
});
3.
$.each(selectValues, function(key, value)
{
$('#mySelect').append($("<option/>", {
value: key,
text: value
}));
});
4.
auxArr = [];
$.each(selectData, function(i, option)
{
auxArr[i] = "<option value='" + option.id + "'>" + option.title + "</option>";
});
$('#selectBox').append(auxArr.join(''));
5.
$.each(items, function(index, item) {
$("#selectList").append(new Option(item.text, item.value));
});
6.pure javascript
var list = document.getElementById("selectList");
for(var i in items) {
list.add(new Option(items[i].text, items[i].value));
}
7.
$('#SelectId').html("<option value='0'>select </option><option value='1'>Laguna</option>");
8.
function populateDropdown(select, data) {
select.html('');
$.each(data, function(id, option) {
select.append($('<option></option>').val(option.value).html(option.name));
});
}