我有一个 onkeyup 方法来自动更新每行标签。表格末尾有一个标签标记,可以自动更新总和。我在将最终标签更新为列的总和时遇到问题,
这是我的代码
<table class="display" cellspacing="0" width="100%" id="paymentTable">
<thead>
<th style="width: 1%;">NO</th>
<th style="width: 30%;">MATA UANG</th>
<th>RATE</th>
<th>SETORAN</th>
<th>TOTAL IDR</th>
</thead>
<tbody>
<?php
$i = 1;
while ($row = $result->fetch_array()) {
echo "<tr>";
echo "<td style='width: 1%; '>$row[curr_id]</td>";
echo "<td>$row[curr_code] - $row[curr_desc]</td>";
echo "<td><input type='hidden' value='$row[conv_rate]' id='convRate$i'>$row[conv_rate]</td>";
echo "<td><input type='text' onkeyup='processCurr($i);' id='inputCurr$i'/></td>";
echo "<td><label id='calculatedCurr$i' class='calculatedCurr'></label></td>";
echo "</tr>";
$i++;
}
?>
</tbody>
</table><br/>
TOTAL = <label id='totalSumPayment'></label>
和我的 JavaScript,
<script>
$('#paymentTable').dataTable();
function processCurr(param){
var inputcurr= $('#inputCurr'+param).val();
var conversion = $('#convRate'+param).val();
$('#calculatedCurr'+param).html(inputcurr * conversion);
calculateSum();
}
function calculateSum(){
var sum = 0;
//iterate through each textboxes and add the values
$(".calculatedCurr").each(function() {
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
// $(this).css("background-color", "#FEFFB0");
}
else if (this.value.length != 0){
// $(this).css("background-color", "red");
}
});
$("#totalSumPayment").val(sum.toFixed(2));
}
</script>
我的问题是,calculateSum() 无法按预期工作,因为 <label>
上没有显示任何值。 。我收到 error = TypeError: this.value is undefined on the firebug。请帮助我......
最佳答案
this
未指向特定元素。您必须使用 $.each 中的参数功能。
$(".calculatedCurr").each(function(key, value) {
//add only if the value is number
if (!isNaN(value) && value.length != 0) {
sum += parseFloat(value);
// $(key).css("background-color", "#FEFFB0");
}
else if (value.length != 0){
// $(key).css("background-color", "red");
}
});
关于javascript - 基于表 TD 的 onkeyup 元素求和表列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36668410/