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 am trying to populate UL on my webpage 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 successfully call loadSavedQueries() because my UL is cleared when select.html('') called. But no items are returned to UL.

Updating ...

After explicit fixes and changes did not work, I found a problem in the controller that did not throw an error, but basically returned empty JSON objects. Once I caught this, the data started to flow down, and the proposed changes did the trick.

+6
source share
2 answers

You can install UL html at the end - no need to clear it first:

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

It is very simple, I will write the code first, then try to come 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); }; }); 

The end result is no comment, 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); }; }); 
0
source

Source: https://habr.com/ru/post/927505/


All Articles