Michal :
I'm trying to create an aggregated table in which the subordinate elements would sum up to their parent elements. Each element contains a class that is equal to the id of its parent element. I have added event listener to every element of the table, so that the summation would go upwards the tree. The code looks roughly as follows:
var x = document.getElementsByName("item.AmountY0");
for (i = 1; i < (x.length - 3); i++) {
x[i].addEventListener("change", function(e) {
if (x[i].tagName == "TD") {
document.getElementById("y0_" + x[i].className).innerHTML =
String(parseInt(document.getElementById("y0_" + x[i].className).innerHTML) + parseInt(x[i].innerHTML));
}
if (x[i].tagName == "INPUT") {
document.getElementById("y0_" + x[i].className).innerHTML =
String(parseInt(document.getElementById("y0_" + x[i].className).innerHTML) + parseInt(x[i].value));
}
}, false);
};
When I check the individual table elements in console, the direct parent element gets updated, but not the other grand-parents. However, when I run the page, nothing happens (and no errors are reported).
The corresponding HTML code is as follows:
@foreach (var item in Model)
{
string y0_id = "y0_" + item.AlphaCode;
string class_parent = item.ParentCode;
string class_parent_right = item.ParentCode + " " + item.CssClassAmt;
<tr class="@item.CssClassRow">
<td hidden="true">@Html.DisplayFor(modelItem => item.FullSymbol)</td>
<td hidden="true">@Html.DisplayFor(modelItem => item.AlphaCode)</td>
<td hidden="true">@Html.DisplayFor(modelItem => item.ParentCode)</td>
<td>@Html.DisplayFor(modelItem => item.Symbol)</td>
<td class="@item.CssClassCell">@Html.DisplayFor(modelItem => item.PositionName)</td>
@if (item.IsFinal[0].Equals('0')) {
<td id=@y0_id class=@class_parent style="text-align: right; width: 120px;" name="item.AmountY0">@Html.DisplayFor(modelItem => item.AmountY0)</td> }
else
{
<td>@Html.TextBoxFor(modelItem => item.AmountY0, new { @id = y0_id, @class = class_parent, @style = "text-align: right; width: 120px;"})</td>
}
<td>@Html.TextBoxFor(modelItem => item.FinNote, new { @class = item.CssClassNote })</td>
<td><a id="js-modal-prompt" class="uk-button uk-button-default uk-button-small" style="line-height: 19px" href="#">+</a></td>
</tr>
Any hints, please?
Zuckerberg :
This issue seems to be related to closures. You can fix it using:
var x = document.getElementsByName("item.AmountY0");
for (i = 1; i < (x.length - 3); i++) {
(function() {
var elm = document.getElementById("y0_" + x[i].className);
x[i].addEventListener("change", function(e) {
if (x[i].tagName == "TD") {
elm.innerHTML = String(parseInt(elm.innerHTML) + parseInt(x[i].innerHTML));
}
if (x[i].tagName == "INPUT") {
elm.innerHTML = String(parseInt(elm.innerHTML) + parseInt(x[i].value));
}
}, false);
}());
};