Konz Mama Konz Mama - 7 months ago 11
SQL Question

summing table column based on onkeyup element of the table TD

I have a onkeyup method to update each row label automatically. At the end of the table there is a label markup that updates the sum automatically. I am having problem updating the final label as the sum of the column,

Here is my code

<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>


and my 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>


My problem is, the calculateSum() doesn't work as expected since no value is showing up on the
<label>
. And I'm getting error = TypeError: this.value is undefined on the firebug. Please help me....

Answer

this is not pointing to a specific element. You have to use the parameters in the $.each function.

      $(".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");
        }
      });