So, I have a function which when called adds a table within a new row of an existing table, complete with results returned in JSON format by a 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 the 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 much as it adds the new table, with heading row and with the closing row. It also will remove the new row if triggered a second time.
The problem is in the $.each
part. I know its receiving the JSON data as inserting an alert before the rowAdd +=
results in a response for each record. It just isn't adding the actual table row in to the rowAdd
string for each record. Its like its just plain skipping that line. Also, there are no JavaScript errors either. So, what am I missing?