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:
selectValues = { "1": "test 1", "2": "test 2" };
for (key in selectValues) {
if (typeof (selectValues[key] == 'string') {
$('#mySelect').append('');
}
}
A clean/simple solution:
This is a cleaned up and simplified version of matdumsa's:
$.each(selectValues, function(key, value) {
$('#mySelect')
.append($('
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().
Answer
Same as other answers, in jQuery fashion:
$.each(selectValues, function(key, value) {
$('#mySelect')
.append($("")
.attr("value",key)
.text(value));
});
No comments:
Post a Comment