How to add json data to select tag in jquery

I have json data below

{ "aaData": [["2","MAC"],["3","Apple"],["5","Windows"],["5","Unix"],["6","Linux"]]} 

And I'm trying to use the jquery code below, but the data does not add with the select tag

 <script type="text/javascript"> $(document).ready(function() { $("#mc_category").change(function() { $.getJSON("/admin/getSubCategory.php", null, function(data) { $("#subcategory").fillSelect(data); }); }); $.fn.fillSelect = function(data) { return this.clearSelect().each(function() { if (this.tagName == 'SELECT') { var dropdownList = this; $.each(data, function(index, optionData) { var option = new Option(optionData.Text, optionData.Value); if ($.browser.msie) { dropdownList.add(option); } else { dropdownList.add(option, null); } }); } }); } }); </script> 
+4
source share
2 answers

You can simply skip the aaData array and use the jQuery appendTo method to add each item to your select box.

I'm not sure what the fillSelect method fillSelect , but here is an implementation that you can replace:

 var sel = $('#subcategory'); for (var i = 0; i < data.aaData.length; i++) { var e = data.aaData[i]; $('<option>').text(e[1]).val(e[0]).appendTo(sel); } 
+5
source
 $("#subcategory").append( $.map(data.aaData,function(index,value){ return $("<option/>").attr("value",value[0]).text(value[1]); }).get(); ); 
+2
source

All Articles