I have a list of persons that I need to display, and for each person there is an input for age.
I need to sum the ages when im writing; I mean if I have 5 persons when I'm on the 5th record, i need the total of previous 4 ages like this one : Calculate sum from number type input fields by javascript
this is my code :
<tr th:each="person : ${persons}">
<td th:text="${person.first_name}"></td>
<td th:text="${person.last_name}"></td>
<td th:text="${person.phone}"></td>
<td><input id="age" class="form-control"
type="text" name="age" th:field="*{ages}">
</td>
</tr>
Total : <input type="text" name="total" id="total"/>
I did this js script, but in total it gives me only the value of first line !!!! Any help ?
<script type="text/javascript">
$(document).ready(function(){
$("#age").each(function() {
$(this).on('input', function(){
calculateSum();
});
log.console("sum :"+sum);
});
});
function calculateSum() {
var sum = 0;
$("#age").each(function() {
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
$("#sum").html(sum.toFixed(2));
}
</script>
2.1. slice the array from 0 to the place of the current value (beacuse slice(0,x) actually slicing the array from 0 to x-1).
2.2 execute the reduce function on the sliced array, you can see an example here: https://www.w3schools.com/jsref/jsref_reduce.asp