What is the best method for adding options to a <select>
from a JavaScript object using jQuery?
I’m looking for something that I don’t need a plugin to do, but I would also be interested in the plugins that are out there.
This is what I did:
JavaScript
x
8
1
selectValues = { "1": "test 1", "2": "test 2" };
2
3
for (key in selectValues) {
4
if (typeof (selectValues[key] == 'string') {
5
$('#mySelect').append('<option value="' + key + '">' + selectValues[key] + '</option>');
6
}
7
}
8
A clean/simple solution:
This is a cleaned up and simplified version of matdumsa’s:
JavaScript
1
6
1
$.each(selectValues, function(key, value) {
2
$('#mySelect')
3
.append($('<option>', { value : key })
4
.text(value));
5
});
6
Changes from matdumsa’s: (1) removed the close tag for the option inside append() and (2) moved the properties/attributes into an map as the second parameter of append().
Advertisement
Answer
The same as other answers, in a jQuery fashion:
JavaScript
1
7
1
$.each(selectValues, function(key, value) {
2
$('#mySelect')
3
.append($("<option></option>")
4
.attr("value", key)
5
.text(value));
6
});
7