Jquery getJSON populate select menu question Jquery getJSON populate select menu question ajax ajax

Jquery getJSON populate select menu question


$.getJSON('selectMenus.php', function(data){    var html = '';    var len = data.length;    for (var i = 0; i< len; i++) {        html += '<option value="' + data[i].monthId + '">' + data[i].month + '</option>';    }    $('select.month').append(html);});

Storing the HTML code in a variable and appending it only once at the end is very important if you care about your app performance.


This should work:

   $.getJSON('selectMenus.php', function(data){        $.each(data, function(index,item) {           $("select.month").append("<option value=" + item.monthID + ">" + item.month + "</option>");     });    });


From the great book jQuery in Action,here is a way to do what you want writing a custom jQuery command:

(function($) {  $.fn.emptySelect = function() {    return this.each(function(){      if (this.tagName=='SELECT') this.options.length = 0;    });  }  $.fn.loadSelect = function(optionsDataArray) {    return this.emptySelect().each(function(){      if (this.tagName=='SELECT') {        var selectElement = this;        $.each(optionsDataArray,function(index,optionData){          var option = new Option(optionData.caption,                                  optionData.value);          if ($.browser.msie) {            selectElement.add(option);          }          else {            selectElement.add(option,null);          }        });      }    });  }})(jQuery);    

And then:

$.getJSON('selectMenus.php',    function(data){      $("select.month").loadSelect(data);   });