Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 685
RSolberg Avatar asked Oct 11 '12 20:10

RSolberg


1 Answers

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(''));
}
like image 112
Gabriel Florit Avatar answered Oct 20 '22 15:10

Gabriel Florit