【问题标题】:Sum of dynamically filled values动态填充值的总和
【发布时间】:2016-04-04 18:22:50
【问题描述】:

我的代码可以分别动态更新食品和服装的总和(当用户输入每个项目的值时)。我想显示总成本(衣服 + 食物投入的总和)。我希望它动态更新。对于每个单独的总和(衣服/食物),我使用了 .keyup。由于衣服的总和和食物的总和不用按键就可以填满,所以我不能使用 keyup 来动态填充总成本。我很难找到一种方法来做到这一点。这是我为该特定部分编写的代码:

$("#total_food, #total_clothes").on("input", function() {
   var sum = $("#total_food").val()+$("#total_clothes").val();
    $("#total_costs").val(sum);
}); 

下面是我的完整代码:

<table>
    <tr>
        <td>(1) Milk 2</td>
        <td><input type="text" class="price_food"></td>
    </tr>
    <tr>
        <td>(2) Eggs</td>
        <td><input type="text" class="price_food"></td>
    </tr>
    <tr>
        <td>Total Cost of Food</td>
        <td><input type="text" disabled="disabled" id="total_food"></td>
    </tr>
    <tr>
        <td>Shoes </td>
        <td><input type="text" class="price_clothes"></td>
    </tr>
    <tr>
        <td>Pants</td>
        <td><input type="text" class="price_clothes"></td>
    </tr>
    <tr>
        <td>Total Cost of Clothes</td>
        <td><input type="text" disabled="disabled" id="total_clothes"></td>
    </tr>
    <tr>
        <td>Total Costs</td>
        <td><input type="text" disabled="disabled" id="total_costs"></td>
    </tr>
</table>
$(document).ready(function() {
    $('.price_food').keyup(function() {
        var sum = 0;
        $('.price_food').each(function() {
            sum += Number($(this).val());
        });
        $('#total_food').val(sum);
    });

    $('.price_clothes').keyup(function() {
        var sum = 0;
        $('.price_clothes').each(function() {
            sum += Number($(this).val());
        });
        $('#total_clothes').val(sum);
    });

    $("#total_food, #total_clothes").on("input", function() {
        var sum = $("#total_food").val() + $("#total_clothes").val();
        $("#total_costs").val(sum);
    });
});

【问题讨论】:

  • 如何动态填充?
  • 总和 - total_food 和 total_clothes 在用户输入每件商品的数量时动态更新(使用 .keyup)。

标签: jquery sum


【解决方案1】:

将整体总计函数分开,然后在每个类输入函数之后调用它,如下所示:

$(document).ready(function() {
    $('.price_food').keyup(function() {
        var sum = 0;
        $('.price_food').each(function() {
            sum += Number($(this).val());
        });
        $('#total_food').val(sum);
        calculatetotalcosts();
    });

    $('.price_clothes').keyup(function() {
        var sum = 0;
        $('.price_clothes').each(function() {
            sum += Number($(this).val());
        });
        $('#total_clothes').val(sum);
        calculatetotalcosts();
    });

    function calculatetotalcosts (){
        var totalcost = Number($("#total_food").val()) + Number($("#total_clothes").val());
        $("#total_costs").val(totalcost);
    };
});

工作 jSFiddle:https://jsfiddle.net/rdawkins/qryx2kmm/4/

【讨论】:

    猜你喜欢
    • 2023-04-08
    • 2021-12-18
    • 2015-11-12
    • 1970-01-01
    • 2021-08-12
    • 2020-06-26
    • 1970-01-01
    • 2022-10-13
    • 1970-01-01
    相关资源
    最近更新 更多