javascript - JQuery, JSON and $.each - string not concatenating -


this question has answer here:

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

Popular posts from this blog

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -

javascript - oscilloscope of speaker input stops rendering after a few seconds -