【问题标题】:jquery make calculation for rows and show the result in the same rowjquery 对行进行计算并在同一行中显示结果
【发布时间】:2015-02-05 11:03:05
【问题描述】:

我的桌子是这样的

<table>
  <tr>
    <td><input type="number" class="product-buying-price"></td>
    <td><input type="number" class="product-selling-price"></td>
    <td class="net-profit"></td>
  </tr>
  <tr>
    <td><input type="number" class="product-buying-price"></td>
    <td><input type="number" class="product-selling-price"></td>
    <td class="net-profit"></td>
  </tr>
  <tr>
    <td><input type="number" class="product-buying-price"></td>
    <td><input type="number" class="product-selling-price"></td>
    <td class="net-profit"></td>
  </tr>
  <tr>
    <td><input type="number" class="product-buying-price"></td>
    <td><input type="number" class="product-selling-price"></td>
    <td class="net-profit"></td>
  </tr>
</table>

您可以看到,在此表中,我有输入值的输入字段。所以有 4 行,其中有相同的 班级名称。像这样我有更多的行,我在这里只使用了 4 行。 现在我希望当我在任何行中输入一些数字时,它应该进行计算并显示 在该行的净利润类别字段中计算后的总计。 所以基本上计算会这样

Product selling price - Product buying price = net-profit

那么有人可以告诉我如何对多行执行此操作,并且计算后相同的结果将显示在同一行中吗?

$('body').on('keyup', '.product-buying-price, .product-selling-price', function() {
    var BuyingPrice = $('.product-buying-price').val();
    var SellingPrice = $('.product-selling-price').val();
    var Total = parseInt(SellingPrice)-parseInt(BuyingPrice);
    console.log(Total);
});

我已经尝试过了,但这一次只给了我一行的结果。如何获取多行的结果?

【问题讨论】:

  • 你试过什么?当您卡在某个地方时,我们可以为您提供帮助,而不是从头开始为您提供整个代码。
  • 您必须为生成的净利润字段提供任何唯一标识符。

标签: jquery


【解决方案1】:
$('.product-buying-price, .product-selling-price').on('blur', function(e) {

    // Get Parent ROW 
    var row = $(this).closest('tr');
    var buying_pr = $('.product-buying-price', row), 
        selling_pr = $('.product-selling-price', row), 
        net_profit = $('.net-profit', row);

    buy_pr = parseFloat(buying_pr.val());
    sell_pr = parseFloat(selling_pr.val());

    if( ! isNaN(buy_pr) && !isNaN(sell_pr) ) {
        net_profit.text( ( sell_pr - buy_pr ).toFixed(2) );
    }
});

DEMO

如果您要使用输入创建动态 tr,请使用:

$('body').on('blur', '.product-buying-price, .product-selling-price', function(e) {

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-08
    相关资源
    最近更新 更多