Zadov
Новичок
Добрый день.
Как сделать так, чтобы сумма по второму столбцу пересчитывалась в зависимости от фильтра?
Сейчас если я набираю в input Andrew, он фильтрует по имени, но сумма остается прежней.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h2>My Customers</h2>
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names..">
<table id="myTable">
<tr>
<th>name</th>
<th>age</th>
</tr>
<tr>
<td>Andrew</td>
<td class="sum">20</td>
</tr>
<tr>
<td>Andrew</td>
<td class="sum">24</td>
</tr>
<tr>
<td>Igor</td>
<td class="sum">26</td>
</tr>
<tr>
<td>Andrew</td>
<td class="sum">31</td>
</tr>
</table>
СУММА = <span id="total"></span>
<script>
var sum = 0;
$('.sum').each(function () {
sum += Number($(this).text());
});
$('#total').text(sum.toFixed(0));
function myFunction() {
var input, filter, table, tr, td, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
</script>
</body>
</html>
Сейчас если я набираю в input Andrew, он фильтрует по имени, но сумма остается прежней.