我有一个产品数据表,用户可以在每一行中输入要购买的产品的金额。我想计算每一行中每种产品的总价格,然后在表格下面计算整个购买的总价格。
这是我的表格:
<table id="productTable">
<thead>
<tr>
<th>Amount</th>
<th>
@Html.DisplayNameFor(model => model.Products[0].Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Products[0].Price)
</th>
<th>Total</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.Products)
{
<tr>
<td>
<input type="number" id="quantityInput" onchange="calcSubTotal()" min="0" value="0" />
</td>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td id="priceLabel">
@Html.DisplayFor(modelItem => item.Price)
</td>
<td id="labelSubTotal"></td>
</tr>
}
</tbody>这些项目来自模型(IList)。我想使用JavaScript将输入值(类型数字)与相应行的价格相乘。
在JavaScript中,我使用getElementById来访问UI元素。如何访问表格中HTML-Input的焦点所在的行?
我的JavaScript:
<script type="text/javascript">
function calcSubTotal() {
var numberInput = document.getElementById('quantityInput');
var val = numberInput.value;
var amount = parseFloat(val);
var priceLabel = document.getElementById('priceLabel');
var priceValue = priceLabel.innerText;
var price = parseFloat(priceValue);
var totalPrice = amount * price;
var subTotalLabel = document.getElementById('labelSubTotal');
subTotalLabel.innerText = totalPrice.toString();
}
</script>发布于 2020-11-06 11:04:30
如果只有一个record.But,你有几个record.Each id,价格和合计是需要区分id的same.You,如下所示:
<table id="productTable">
//..
<tbody>
@{
int i = 0; //add this..
}
@foreach (var item in Model.Products)
{
<tr>
<td>
//change the onchange function...
<input type="number" id="quantityInput" onchange="calcSubTotal(this,@i)" min="0" value="0" />
</td>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td id="priceLabel_@i"> //change here...
@Html.DisplayFor(modelItem => item.Price)
</td>
<td id="labelSubTotal_@i"></td> //change here...
</tr>
i++; //add this....
}
</tbody>
</table>
@section Scripts
{
<script type="text/javascript">
function calcSubTotal(element,index) {
var numberInput = $(element).val();
var amount = parseFloat(numberInput);
var priceLabel = document.getElementById('priceLabel_'+index);
var priceValue = priceLabel.innerText;
var price = parseFloat(priceValue);
var totalPrice = amount * price;
var subTotalLabel = document.getElementById('labelSubTotal_'+index);
subTotalLabel.innerText = totalPrice.toString();
}
</script>
}结果:

https://stackoverflow.com/questions/64697359
复制相似问题