Home > Blockchain >  Can't get values of input with js
Can't get values of input with js

Time:06-19

I have a inputs in loop using thymeleaf, I need when hover each iteration get the value and calculate sum

 <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" 
                        type="text" name="age" th:field="*{ages}">
            </td>
    </tr>

Total : <input type="text" name="sum" id="sum"/>

My js script :

<script type="text/javascript">
    $(document).ready(function(){
          $("#age").each(function() {

            $(this).on('input', function(){
              calculateSum();
            });
            
            console.log("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>

My code give me on total only the first value (like it doesnt work on 2nd iteration), i dont know why !!

CodePudding user response:

Ids should be unique on a page; as such, id selectors usually only return the first element with that id. You should use classes instead.

<input   type="text" name="age">

Your selectors should then become:

$(".age").each(function(){
    // ...
});
  • Related