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

标签 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> 上没有显示任何值。 。我收到 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/

相关文章:

php - 我试图解析 fwrite 中的变量,但它不喜欢我的双引号

javascript - 如何在javascript中增加数据索引

javascript - 如何减少 Jquery/Ajax 代码 -> 删除重复

javascript - 单词中每个第一个字符和任何大写字母的正则表达式

javascript - 按顺序加载两个 jqgrids(序列 ajax 调用)

javascript - 脚本无法使用不存在的 ID,除非 $.getJSON 附加它

javascript - Deferred 和 Promise 功能无法正常工作

php - where没有按预期工作

php - mysql 两个查询

javascript - DataTables.js 对包含带有整数文本的 HTML 链接的列进行排序