开发者

How to add json data into select tag in jquery

I have json data as below

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

And I try with below jquery code but data not add with select tag

<开发者_C百科;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>


You can just loop through 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 does, but here's an implementation that you can replace it with:

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


$("#subcategory").append(
     $.map(data.aaData,function(index,value){
          return $("<option/>").attr("value",value[0]).text(value[1]);
     }).get();
 );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜