patternjavascriptCritical
What is the best way to add options to a select from a JavaScript object with jQuery?
Viewed 0 times
objectwithfromjquerythebestaddwayoptionswhat
Problem
What is the best method for adding options to a `` 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:
A clean/simple solution:
This is a cleaned up and simplified version of matdumsa's:
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().
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:
selectValues = { "1": "test 1", "2": "test 2" };
for (key in selectValues) {
if (typeof (selectValues[key] == 'string') {
$('#mySelect').append('' + selectValues[key] + '');
}
}A clean/simple solution:
This is a cleaned up and simplified version of matdumsa's:
$.each(selectValues, function(key, value) {
$('#mySelect')
.append($('', { value : key })
.text(value));
});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().
Solution
The same as other answers, in a jQuery fashion:
$.each(selectValues, function(key, value) {
$('#mySelect')
.append($("")
.attr("value", key)
.text(value));
});Code Snippets
$.each(selectValues, function(key, value) {
$('#mySelect')
.append($("<option></option>")
.attr("value", key)
.text(value));
});Context
Stack Overflow Q#170986, score: 1486
Revisions (0)
No revisions yet.