jQuery: Best practice to populate drop down?
The example I see posted all of the time seems like it's suboptimal, because it involves concatenating strings, which seems so not jQuery. It usually looks like this:
$.getJSON("/Admin/GetFolderList/", function(result) {
for (var i = 0; i < result.length; i++) {
options += '<option value="' + result[i].ImageFolderID + '">' + result[i].Name + '</option>';
}
});
Is there a better way?
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));
});
$.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
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...
Or maybe:
var options = $("#options");
$.each(data, function() {
options.append(new Option(this.text, this.value));
});