Reputation: 10214
I know what the problem is, but I am unsure how to fix it.
It is looping through each tr, and then posting to a url to retrieve a total, by the time the post returns a value, the loop has reached the last tr in the table.
So when the .done callback takes place, $tr is referencing the last row in the table.
What is the best approach to reference the original $tr that the post call was made for?
$div.find('table tbody tr').each(function() {
$tr = $(this);
associationId = $tr.data('id');
$.post(settings.UrlFetch, {competition_id: settings.CompetitionId, association_id: associationId})
.done(function (res) {
if (res.success) {
$tr.find('.total').html('$' + Number(res.data.total).toFixed(2));
} else {
alert(res.errors);
}
})
.fail(function (res) {
alert("Unknown Error Occurred");
});
});
Upvotes: 0
Views: 33
Reputation: 388406
The problem is you are using a global variable $tr
which is overriden in each iteration of the each
callback, you need to use a closure variable(by declaring $tr
using var
) to have a local instance of $tr
in each call of the callback
$div.find('table tbody tr').each(function () {
var $tr = $(this); //use local variable
associationId = $tr.data('id');
$.post(settings.UrlFetch, {
competition_id: settings.CompetitionId,
association_id: associationId
}).done(function (res) {
if (res.success) {
$tr.find('.total').html('$' + Number(res.data.total).toFixed(2));
} else {
alert(res.errors);
}
}).fail(function (res) {
alert("Unknown Error Occurred");
});
});
Upvotes: 1