简体   繁体   中英

How can I create this select list from a JSON object using JQuery?

Yeah, I have 3 or 4 different answers on the same subject but I'm struggling to combine them to create what I need. I serialize my results using Json.Net which results in the following object:

"[  { "Id": 1, "OrderInList": 1  },
    { "Id": 2, "OrderInList": 2  },
    { "Id": 4, "OrderInList": 3  }
]"

I'd like the option value and text to be the OrderInList value (I'll use the Id with something else later).

I've currently got the following code, but it creates 143 option boxes. I can see why it's doing it, but I'm not sure how to alter it to get it to work.

    $.getJSON("/Json/GetOrderSelectList?parentCategoryId=" + postData, null, function (jsonResult) {
        $('#orderInList').attr('enabled', 'true');
        $.each(jsonResult, function() {
            $.each(this, function(index, item) {
                                $('#orderInList').append(
                                    $("<option></option>")
                                        .text(index)
                                        .val(index)
                                );

            });
        });

Any help would be appreciated!

I think you're trying something like this:

var jsonResult = [{
    "Id": 1,
    "OrderInList": 1},
{
    "Id": 2,
    "OrderInList": 2},
{
    "Id": 4,
    "OrderInList": 3}
]

$('#orderInList').attr('enabled', 'true');
$.each(jsonResult, function() {
   $('#orderInList').append(
        $("<option></option>").text(this.Id).val(this.OrderInList);
   );
});​

DEMO

Full code

$.getJSON("/Json/GetOrderSelectList?parentCategoryId=" + postData, function(jsonResult) {
    $('#orderInList').attr('enabled', 'true');
    $.each(jsonResult, function() {
        $('#orderInList').append(
            $("<option></option>").text(this.Id).val(this.OrderInList)
        );
    });
});​

You do not need the extra call to .each that is nested within the first call to .each. Just pass the items and the index in the first .each call then create your element. Try this:

var json = [  { "Id": 1, "OrderInList": 1  },
    { "Id": 2, "OrderInList": 2  },
    { "Id": 4, "OrderInList": 3  }
];

function createSelect(options){
    $.each(options,function(index,item){
           $("#orderInList").append($("<option></option>").attr("value", item.OrderInList).text(item.OrderInList));

    });
}

$(document).ready(function(){
createSelect(json);
});

Working Example: http://jsfiddle.net/BzC9N/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM