基于表TD的onkeyup元素求和表列

时间:2016-04-16 19:00:46

标签: javascript php jquery mysql ajax

我有一个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>上没有显示任何值。我收到错误= TypeError:在firebug上未定义this.value。请帮帮我......

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

您的代码存在以下问题。

//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");
            }
        }); 

这里 .calculatedCurr 元素不是文本框。它们是标签。所以 this.value 不会得到正确的值。正确的值是在内部html中 .calculatedCurr 元素。

相关问题