How to calculate sum in th:each thymeleaf?

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"/>