如何在MVC中的动态表中查找列值的总和
我有动态表的视图。 加载页面时,可能存在现有行。 用户也可以添加新行并保存相同的行。 在表中有两列net_amt和quantity。 在表的底部我需要显示这些列的总数是否可能。 请分享一些有关相同的想法。
表的动态模板
视图内的表
@if (Model != null) { for (int i = 0; i < Model.provider_service_dtls.Count; i++) { @Html.TextBoxFor(m => m.provider_service_dtls[i].net_amt, new { style = "width: 40px;"}) @Html.TextBoxFor(m => m.provider_service_dtls[i].quantity, new { style = "width: 25px;" }) } }
浏览器中的表视图
打开请求时,将有零行或更多行。 添加行并在填写文本框中的值后,总计应自动更改。 我认为它只能通过jquery,但我完全被困在这里。 请帮忙
您将需要javascript / jquery来处理文本框的.change()
事件。 由于您可以动态地向表中添加新行,因此您还需要使用.on()
来使用事件委派。 以下示例基于您的表具有id="myTable"
并且它包含第二个tbody
元素,其中行id="totals"
HTML
.... // you for loop for generating existing rows ## // insert existing total ## // insert existing total // blank (delete button column
脚本
var body= $('#myTable').children('tbody').first(); var totals = $('#totals'); body.on('change', 'input[type="text"]', function() { var total = 0; var columnIndex = $(this).closest('td').index(); var rows = body.find('tr'); $.each(rows, function() { var amount = $(this).children('td').eq(columnIndex).children('input[type="text"]').val(); total += new Number(amount); }); totals.children('td').eq(columnIndex).text(total); });
请参阅此小提琴以获取工作示例
尝试这个小数量添加function:
function recalculate() { $('tr').each(function() { $(this).find('button').parent().remove(); $(this).append(" "); }); } $('input').change(function() { recalculate() }); recalculate();