Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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>
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

  1. put all of the ages in array
  2. On every place you want to show the sum of the previous ages:

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!