jQuery: Best practice to populate drop down?
Sure - make options
an array of strings and use .join('')
rather than +=
every time through the loop. Slight performance bump when dealing with large numbers of options...
var options = [];
$.getJSON("/Admin/GetFolderList/", function(result) {
for (var i = 0; i < result.length; i++) {
options.push('<option value="',
result[i].ImageFolderID, '">',
result[i].Name, '</option>');
}
$("#theSelect").html(options.join(''));
});
Yes. I'm still working with strings the whole time. Believe it or not, that's the fastest way to build a DOM fragment... Now, if you have only a few options, it won't really matter - use the technique Dreas demonstrates if you like the style. But bear in mind, you're invoking the browser's internal HTML parser i*2
times, rather than just once, and modifying the DOM each time through the loop... with a sufficient number of options. you'll end up paying for it, especially on older browsers.
Note: As Justice points out, this will fall apart if ImageFolderID
and Name
are not encoded properly...
Andreas Grech was pretty close... it's actually this
(note the reference to this
instead of the item in the loop):
var $dropdown = $("#dropdown");
$.each(result, function() {
$dropdown.append($("<option />").val(this.ImageFolderID).text(this.Name));
});
Or maybe:
var options = $("#options");
$.each(data, function() {
options.append(new Option(this.text, this.value));
});
$.getJSON("/Admin/GetFolderList/", function(result) {
var options = $("#options");
//don't forget error handling!
$.each(result, function(item) {
options.append($("<option />").val(item.ImageFolderID).text(item.Name));
});
});
What I'm doing above is creating a new <option>
element and adding it to the options
list (assuming options
is the ID of a drop down element.
PS My javascript is a bit rusty so the syntax may not be perfect