RSolberg
RSolberg

Reputation: 26972

Using JSON To Populate UL With jQuery

This is my JSON data

[
    {"CountyId":2,"Name":"Snohomish","StateId":1,"State":null,"Plans":null},    
    {"CountyId":1,"Name":"Whatcom","StateId":1,"State":null,"Plans":null}
]

I'm attempting to populate a UL on my web page with this data.

function loadSavedCounties() {
    $.post("/Plans/GetPlanCounties/",
        { planId: $("#PlanId").val() },
        function (data) {
            populateSavedCounties($("#SavedCounties"), data);
        }
    );
}
function populateSavedCounties(select, data) {
    select.html('');
    var items = [];
    $.each(data, function (id, option) {
        items.push('<li>' + option.Name + '</li>');
    });  
    select.append(items.join(''));
}

I know that i'm successfully calling the loadSavedQueries() because my UL is being cleared out with the select.html('') call. But no items are being put back into the UL.

Update...

After the obvious fixes and changes not working, I discovered an issue within the controller that wasn't throwing an error, but was basically returning empty JSON objects. Once I caught this, the data started flowing down and the changes suggested did the trick.

Upvotes: 8

Views: 11889

Answers (2)

Gabriel Florit
Gabriel Florit

Reputation: 2918

You can set the UL's html at the end - no need to clear it out first:

function populateSavedCounties(select, data) {
    var items = [];
    $.each(data, function (id, option) {
        items.push('<li>' + option.Name + '</li>');
    });  
    select.html(items.join(''));
}

Upvotes: 13

SpYk3HH
SpYk3HH

Reputation: 22570

This is very easy, I'll write up code first, then try to go back and explain.

Script

// You obviously know how to use .post
$.post("/Plans/GetPlanCounties/", { planId: $("#PlanId").val() }, function(data) {
    // out of simplicity, i did not create a seperate function, however you seem to know how to move functions around
    // below of course i simply assign a variable for reuse to the element you want
    var $this = $("#SavedCounties").empty();
    // instead of .each, I went on the premise that your data is returned exactly as stated above,
    // in which case, a simple old school for statement is easiest
    for (x in data) {
        // this is real simple, the first part creates a jQuery object of a List Element
        // the text part adds the text too it (aka, html you were wanting)
        // the last part appends the Li to the END of the UL
        $("<li />").text(data[x].Name).appendTo($this);
    };
});

Final result without comments, is very short and sweet

$.post("/Plans/GetPlanCounties/", { planId: $("#PlanId").val() }, function(data) {
    var $this = $("#SavedCounties").empty();
    for (x in data) {
        $("<li />").text(data[x].Name).appendTo($this);
    };
});

Upvotes: 0

Related Questions