I have the following HTML code:
<table class="viewTable">
<tr>
<td>Price</td>
</tr>
</table>
and I want to insert data dynamically using Javascript as follows:
var totalPrice = 0;
map.each(function(key , value , i) {
params = {};
params.id = key;
// get datas from Controller class via ajax
ajax(url, params, false, function(result) {
totalPrice += setData(result , key , value);
});
});
// alert("something!"); // this may satisfy my problem.. I have no idea..
// Total Price shown on last row
$('table.viewTable tr:last').after("<tr class='title_bar'><td colspan='5' style='text-align: right;padding-right: 35px;'>"+num2Currency(totalPrice)+"</td></tr>");
The setData
function is:
function setData(result , partsId , count) {
var price = result.price;
html = [];
html.push("<tr>");
html.push("<td><div>"+price+"</div></td>");
html.push("</tr>");
$('table.viewTable').append(html.join(''));
return price;}
I used the map function from Jade's answer to this question: Map in JavaScript.
My problem is either the displaying of the results or the procedure itself isn't correct. It should be inserting price rows first and then the totalPrice row afterwards; instead, the order is reversed, with totalPrice appearing first followed by the price rows. When I inserted an alert statement before insertion of totalPrice, it worked fine. Any suggestions? What's wrong with my code? Is jQuery compiled asynchronously?