Does anyone know of a technique to programmatically create an HTML select list including options using JQuery?
8 Answers
I know this is old, but what the hey:
$selectBox.html($.map(myArray, function(){
return $('<option/>', {text: this});
}));
1 Comment
Bobort
Great method for the functional programming paradigm, which we all need to shift to!
Here's a variation - based on previous answers in this thread - where all but the select-input options can be specified via an input JSON object:
Would be interesting to see if the options array can somehow be specified in that JSON input?
var fruitListProfile = {
id : someKey,
class : 'fruit_list',
style : 'margin-right: 20px; '
};
var selectInput = $('<select/>', fruitListProfile);
var fruitOptions = ['apple', 'cherry', 'kiwi'];
for (var i in fruitOptions) {
selectInput.append($('<option/>').html(fruitOptions[i]));
}
Comments
Here is another version of an answer to the question using ajax to fetch a json response used to create the select list with key value pairs
$.ajax({
type: 'post',
url: 'include/parser.php',
data: {
mode: 'getSubtypes',
type: type
},
success: function (response) {
var mySubtype = document.getElementById("Component");
var components = $.parseJSON(response);
var selectList = document.createElement("select");
selectList.id = "subtype";
selectList.name = "subtype";
mySubtype.appendChild(selectList);
$('#subtype').append('<option value="">Select ...</option>');
$.each(components, function(k, v) {
var option = new Option(v, k);
$('#subtype').append($(option));
});
}
});
Comments
If you have already <select> list somewhere in DOM, reuse it and make it empty from previous user interactions...
// Call existing list, chain empty()
var my_list = $("#my_list").empty();
// Build list
$(my_arr).each(function() {
my_list.append($("<option/>").attr(\'value\',this.item_id).text(this.item_name));
});