jQuery: Best practice to populate drop down?

Jeff Putz picture Jeff Putz · May 2, 2009 · Viewed 363.6k times · Source

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?

Answer

Jeff Putz picture Jeff Putz · May 4, 2009

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));
});