我的页面中有这样的表格:
<table class="table table-bordered table-striped">
<caption>
<h3>Itens do Estrutural</h3>
<div class="input-group input-group-lg col-md-9">
<span class="input-group-addon">Filtrar:</span>
<input type="text" name="filterbox" id="filterbox" class="form-control" placeholder="Type your search here ..." />
</div><br />
</caption>
<thead>
<tr>
<th>Company</th>
<th>Description</th>
<th>Value</th>
</tr>
<tr class="info">
<td colspan="2" class="text-right">TOTAL:</td>
<td class="total text-right"></td>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td class="text-center">@Html.DisplayFor(modelItem => item.Company)</td>
<td>@Html.DisplayFor(modelItem => item.Description)</td>
<td class="valor text-right">@Html.DisplayFor(modelItem => item.Value)</td>
</tr>
}
</tbody>
<tfoot>
<tr class="info">
<td colspan="2" class="text-right">TOTAL:</td>
<td class="total text-right"></td>
</tr>
</tfoot>
</table>
当文档准备就绪时,它计算了具有类 valor 的列的总和,并且它显示在表的头部和底部,类别为 total 的列
这个想法是用户可以过滤在名为 filterbox 的输入文本上输入任何内容的行,因此应该重新计算总数。
此时我可以使用jQuery代码过滤行:
$(document).ready(function () {
var $rows = $(".table tbody tr");
var total = 0;
$rows.each(function () {
total += parseFloat($(this).find(".valor").text().replace(/\./g, "").replace(",", "."));
});
$("#filterbox").keyup(function () {
var filtertext = $(this).val();
var regex = new RegExp(filtertext, 'i');
$rows.hide().filter(function () {
return regex.test($(this).text());
}).show();
});
$(".total").html(formataTotal(total.toFixed(2)));
});
function formatTotal(num) {
var parts = num.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ".");
return parts.join(",");
}
我已尝试以下方法来重新计算总数,但它不起作用:
$("#filterbox").keyup(function () {
var filtertext = $(this).val();
var regex = new RegExp(filtertext, 'i');
$rows.hide().filter(function () {
return regex.test($(this).text());
}).each(function () {
total += parseFloat($(".table tbody tr").find(".valor").text().replace(/\./g, "").replace(",", "."));
}).show();
});
如何对过滤行时重新计算的值求和?
感谢您的关注。 保罗里卡多费雷拉
答案 0 :(得分:1)
试试这个:
$(document).ready(function () {
var $rows = $(".table tbody tr");
var total = 0;
$rows.each(function () {
total += parseFloat($(this).find(".valor").text().replace(/\./g, "").replace(",", "."));
});
$("#filterbox").keyup(function () {
var filtertext = $(this).val();
var regex = new RegExp(filtertext, 'i');
$rows.hide().filter(function () {
return regex.test($(this).text());
}).show();
$(".table tbody tr:visible").each(function () {
total += parseFloat($(this).find(".valor").text().replace(/\./g, "").replace(",", "."));
});
$(".total").html(formataTotal(total.toFixed(2)));
});
$(".total").html(formataTotal(total.toFixed(2)));
});
function formatTotal(num) {
var parts = num.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ".");
return parts.join(",");
}