3

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!

2 Answers 2

8

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)
        );
    });
});​
Sign up to request clarification or add additional context in comments.

1 Comment

Excellent. +1 for jsfiddle, looks like a really handy website for this type of stuff. Thanks loads.
0

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.