This is when the “context” of the input that matters: you want to update the sum that is in the same column where the input element was updated.
What you can do is:
- Get the index of the
<td>
element the input belongs to - Calculate the sum of all expenses belonging to the same column. This is done by filtering (using
.filter()
) all.expenses
elements to ensure that their parent’s<td>
index matches that you’ve determined in step 2 - Set the sum on the corresponding
.expenses_sum
element in the same column. This is again, done by filtering all.expenses_sum
elements and only getting the one whose parent<td>
index matches
Some additional pro-tips:
- Listen to the
onInput
event. For input elements, that coversonKeyUp
andonChange
events, for convenience. - Use
<input type="number" />
to prevent users from erroneously entering non-numerical characters - Use
<input readonly />
on the.expenses_sum
element, so that users don’t fiddle with that sum by their own - Remember to cast the value of the input elements to a number. This can be done by using the
+
operator, i.e.+this.value
. Remember that as per spec, all input elements, regardless theirtype
, always has their value in type ofstring
- Chain
.each(calculateSum)
to your original selection, so that you also compute the sum when the page is first loaded, i.e.$(".expenses").on('input', calculateSum).each(calculateSum);
. This is very helpful when the.expenses
elements might be pre-populated with values from the server-side (or if you have manually definedvalue="..."
), for example.
See proof-of-concept below:
$(document).ready(function() {
$(".expenses").on('input', calculateSum).each(calculateSum);
});
function calculateSum() {
// Get the index of the parent `<td>` element
var cellIndex = $(this).closest('td').index();
// Get the values of expenses in the same column as the `<td>` element
var allExpensesInSameColumn = $('.expenses').map(function() {
if ($(this).closest('td').index() !== cellIndex)
return;
return +this.value;
}).get();
// Calculate the sum from returned array of values
var sumOfExpensesInSameColumn = allExpensesInSameColumn.reduce(function(acc, curVal) {
return acc + curVal;
});
// Set the sum on the `.expenses_sum` element in the corresponding column
$('.expenses_sum').each(function() {
if ($(this).closest('td').index() !== cellIndex)
return;
this.value = sumOfExpensesInSameColumn;
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
<tr>
<th>sl</th>
<th>TA</th>
<th>DA</th>
</tr>
<tr>
<td>1</td>
<td><input class="expenses" type="number" /></td>
<td><input class="expenses" type="number" /></td>
</tr>
<tr>
<td>2</td>
<td><input class="expenses" type="number" /></td>
<td><input class="expenses" type="number" /></td>
</tr>
<tr>
<td>Total</td>
<td><input class="expenses_sum" readonly></td>
<td><input class="expenses_sum" readonly></td>
</tr>
</table>
solved sum of column using jquery [closed]