javascript - JQuery, JSON and $.each - string not concatenating -
this question has answer here:
- how return response asynchronous call? 21 answers
so, have function when called adds table within new row of existing table, complete results returned in json format restful api.
code:
$(".transactionviewbutton").each(function(){ var $this = $(this); $this.on("click", function(){ if($(this).closest("tr").next("tr").attr('id') != "itemsrow"){ var rowadd = "<tr id='itemsrow'><td colspan='8'><table class='table table-striped table-hover bureau-customer-table'><thead><tr><th>item id</th><th>item name</th><th>cost</th><th>fsm amount</th><th>end cost</th></tr></thead><tbody>"; $.getjson("transactionitem.json", function(data){ $.each(data, function (key, val){ rowadd += "<tr><td>" + val.id + "</td><td>" + val.name + "</td><td>" + val.cost + "</td><td>" + val.fsm+ "</td><td>" + val.endcost + "</td></tr>"; }); }); rowadd += "</tbody></table></td></tr>"; $(this).closest("tr").after(rowadd); } else { $(this).closest("tr").next("tr").remove(); } }); });
and json test data:
[{ "id": "123", "name": "food item 1", "cost": "0.50", "fsm": "0.00", "endcost": "0.50" },{ "id": "124", "name": "food item 2", "cost": "0.50", "fsm": "0.00", "endcost": "0.50" },{ "id": "125", "name": "food item 3", "cost": "0.50", "fsm": "0.00", "endcost": "0.50" }]
the function works as adds new table, heading row , closing row. remove new row if triggered second time.
the problem in $.each
part. know receiving json data inserting alert before rowadd +=
results in response each record. isn't adding actual table row in rowadd
string each record. its plain skipping line. also, there no javascript errors either. so, missing?
the $.get
asynchronous. means code dependant on result of request needs placed in callback. try this:
$.getjson("transactionitem.json", function(data){ var rowadd = "<tr id='itemsrow'><td colspan='8'><table class='table table-striped table-hover bureau-customer-table'><thead><tr><th>item id</th><th>item name</th><th>cost</th><th>fsm amount</th><th>end cost</th></tr></thead><tbody>"; $.each(data, function (key, val){ rowadd += "<tr><td>" + val.id + "</td><td>" + val.name + "</td><td>" + val.cost + "</td><td>" + val.fsm+ "</td><td>" + val.endcost + "</td></tr>"; }); rowadd += "</tbody></table></td></tr>"; $(this).closest("tr").after(rowadd); });
Comments
Post a Comment