I'm using Asp.net mvc core 2.2 the calculations below works fine when I try in jsfiddle.net however the calculation is not working, do nothing as it displays "0.00" when I try in Visual Studio.
My view codes:
Code starts here- table class="tbl table table-striped">
TABLE HEADERS
@{ foreach (var item in Model.Tblstsabit)
{
<tr style="padding:50px;">
<td style="text-align:center">
@Html.DisplayFor(c => item.StokKodu)
</td>
<td style="text-align:center">
@Html.DisplayFor(c => item.StokAdi)
</td>
<td style="text-align:center">
@Html.DisplayFor(c => item.SatisFiat1, new { @class = "unitprc" })
@*for this part I tried <input type="text" class="unitprc"> it works in jsfiddle.net but not in VS*@
</td>
<td style="text-align:center;">
<input type="text" class="qtt" />
</td>
<td style="text-align:center;">
<input type="number" max="100" class="col-9" />
</td>
<td style="text-align:center;">
<input type="number" max="100" class="col-9" />
</td>
<td style="text-align:center;">
<input type="text" readonly value="0.00" class="sum" />
</td>
<td style="text-align:center">
<button type="submit" class="btn btn-danger" asp-action="Remove" asp-route-stokkodu="@item.StokKodu">
<img src="~/resimler/garbage.png" />
</button>
</td>
</tr>
}
}
Total Sum:
<div class="col-4">
<label>Total Sum</label>
<input id="gsum" value="0.00" readonly />
</div>
Script:
<script>
$(".tbl").on("change keyup keydown paste propertychange bind mouseover", function () {
calculateSum();
});
// function
function calculateSum() {
var sum = 0;
$(".sum").each(function () {
if (!isNaN(this.value) && this.value.length != 0) {
var quantity = $(this).closest("tr").find("input.qtt:text").val();
var valor = $(this).closest("tr").find("input.unitprc:text").val();
var subTot = (quantity * valor);
$(this).val(subTot.toFixed(2));
sum += parseFloat(subTot.toFixed(2));
}
});
$('#gsum').val(sum.toFixed(2));
}
</script>
I have been looking these codes about 9 hours and couldnt find any reason why it is not working. Can Foreach loop be the reason? PS: If you are going to try in jsfiddle.net you should write the code between table tag which has a "cls" named class
Try to make the following changes
In the view code , add class = "unitprc"
to the <td></td>
where @Html.DisplayFor(c => item.SatisFiat1, new { @class = "unitprc" })
is located , like below
<td style="text-align:center" class = "unitprc">
@Html.DisplayFor(c => item.SatisFiat1)
</td>
2.Make some changes in your jquery like below
$("input.qtt:text").on("change paste keyup" ,function () {
calculateSum();
});
// function
function calculateSum() {
var sum = 0;
$(".sum").each(function () {
if (!isNaN(this.value) && this.value.length != 0) {
var quantity = $(this).closest("tr").find("input.qtt:text").val();
var valor = $(this).closest("tr").find(".unitprc").html();
var subTot = (quantity * valor);
$(this).val(subTot.toFixed(2));
sum += parseFloat(subTot.toFixed(2));
}
});
$('#gsum').val(sum.toFixed(2));
}
How it works