Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

600
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda