【问题标题】:DataTables and jQuery to Perform Calculations in a TableDataTables 和 jQuery 在表中执行计算
【发布时间】:2017-08-29 05:27:21
【问题描述】:

我想通过更改单元格内的输入值并使用 jquery onkeyup 事件在表格中执行数学运算。

<table id="GVHabvar">
    <tbody>
        <tr>
            <td>
                <input id="cantidad" name="cantidad" type="text" class = "calculo">
            </td>
            <td>
                <input id="precio" name="precio" type="text" class = "calculo">
            </td>
            <td>
                <input id="valor" name="valor" type="text">
            </td>
        </tr>
        <tr>
            <td>
                <input id="cantidad" name="cantidad" type="text" class = "calculo">
            </td>
            <td>
                <input id="precio" name="precio" type="text" class = "calculo">
            </td>
            <td>
                <input id="valor" name="valor" type="text">
            </td>
        </tr>
        <tr>
            <td>
                <input id="cantidad" name="cantidad" type="text" class = "calculo">
            </td>
            <td>
                <input id="precio" name="precio" type="text" class = "calculo">
            </td>
            <td>
                <input id="valor" name="valor" type="text">
            </td>
        </tr>
    </tbody>
</table>

这是我的尝试,但它不适用于数据表(例如分页)

    $(document).ready(function () {
        var filas = $("#GVHabvar tbody tr");
        filas.each(function (index) {
            var fila = $(this);
            fila.find('.calculo').on('keyup', function () {
                var cantidad = ($.isNumeric(fila.find("#cantidad").val())) ? fila.find("#cantidad").val() : 0;
                var precio = ($.isNumeric(fila.find("#precio").val())) ? fila.find("#precio").val() : 0;
                var valor = parseInt(cantidad, 10) * parseInt(precio, 10);
                fila.find('#valor').val(valor);
            });
        });
    });

【问题讨论】:

    标签: jquery math datatables multiplication


    【解决方案1】:

    一种方法是使用数据表rowCallback。此事件在绘制每一行后触发,可用于绑定您的 keyup 事件。正如您发现的那样,您这样做的方式只会影响可见的表格数据。

    var table = $('#GVHabvar').DataTable({
        "rowCallback": function (row, data, index) {
            var fila = $(row);
            fila.find('.calculo').on('keyup', function () {
               var cantidad = ($.isNumeric(fila.find("#cantidad").val())) ? fila.find("#cantidad").val() : 0;
               var precio = ($.isNumeric(fila.find("#precio").val())) ? fila.find("#precio").val() : 0;
               var valor = parseInt(cantidad, 10) * parseInt(precio, 10);
               fila.find('#valor').val(valor);
           });
        }
    });
    

    这是一个有效的jsfiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-16
      • 2016-11-01
      • 2015-03-25
      • 2010-11-12
      • 1970-01-01
      相关资源
      最近更新 更多