无法使用 js 获取输入值



我有一个使用thymeleaf的输入循环,我需要在悬停每次迭代时获得值并计算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" class="form-control"
type="text" name="age" th:field="*{ages}">
</td>
</tr>
Total : <input type="text" name="sum" id="sum"/>
我的js脚本:
<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>

我的代码只给了我第一个值(就像它不工作在第二次迭代),我不知道为什么!!

id在一个页面上应该是唯一的;因此,id选择器通常只返回具有该id的第一个元素。你应该用类来代替。

<input class="age" class="form-control" type="text" name="age">

你的选择器应该变成:

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

最新更新