I have a select field and a button:
<select id="mylist"></select>开发者_开发问答;
<input type="button" id="btn" value="update">
my js code:
var btn=$('#btn');
btn.click(function(){
var optionList = GET_LIST();// GET_LIST() returns a array of strings which is the option texts.
//How to use optionList to update the options in <select> ?
});
How to update my options list with optionList
in select tag ?
EDIT: Based on note from @amsutil alternate using html:
var btn=$('#btn');
btn.click(function(){
var optionList = GET_LIST();
var select = $("#mylist");
select.html("");
var optionsHTML = "";
$.each(optionList, function(a, b){
optionsHTML += "<option>" + b + "</option>";
});
select.html(optionsHTML);
});
Try this:
var btn=$('#btn');
btn.click(function(){
var optionList = GET_LIST();
var select = $("#mylist");
select.empty();
$.each(optionList, function(a, b){
select.append("<option>" + b + "</option>");
});
});
If you are wanting to create select options from an array, your values and label text will match. These will need to be stored in an object if you want to have values and text be different:
var btn = $('#btn');
btn.click(function() {
var optionList = GET_LIST();
var element = $('#mylist');
$.each(optionList, function(index, value) {
element.append('<option value="' + value + '">' + value + '</option>');
});
});
I see a few answers using 'append', but this creates too many DOM manipulations. If you have a large number of values in your array, it could slow the site down. It's much better to store all of the new options in a string, and do one DOM manipulation at the end.
Demo: http://jsbin.com/ubotu4/
Using $.map()
to convert an array of strings into an array of option elements:
var optionList = GET_LIST();
var options = $.map(optionList, function (item, i) {
return $('<option>', {text: item}); // Convert string into <option>
});
$('#mylist').empty().append(options); // Append to the <select>
精彩评论