javascript Jquery 从字段计算小计 - 按类别和总计的数量和价格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22047513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 22:16:58  来源:igfitidea点击:

Jquery calculate sub total from fields - qty and price by class and grand Total sum

javascriptjquery

提问by thecore7

I have prepared this jsfiddle

我已经准备好了这个jsfiddle

The problem is that I have many rows containing product qty * price = sub total This also must dynamically calculate grand total for all sub total amounts. And the biggest problem is the trigger since we may not have change trigger on the qtyselect fields.. really complicated for me. I am so far stacked here:

问题是我有很多行包含产品数量 * 价格 = 小计 这也必须动态计算所有小计的总计。最大的问题是触发器,因为我们可能在qty选择字段上没有更改触发器......对我来说真的很复杂。我到目前为止堆在这里:

$(document).ready(function() {    
    var qty=$('.qty').val();
    var price = $('.price').val();
    var sum = 0;

    $('.amount').each(function() {
        sum += parseFloat($(this).text());
    });
});

Please give me idea for:

请给我的想法:

  1. Which trigger to use so it can calculate on page load as well and if qty dropdown is changed too.
  2. How to calculate each row first
  1. 使用哪个触发器,以便它也可以计算页面加载以及数量下拉列表是否更改。
  2. 如何先计算每一行

thank you for your help and time in advance!

提前感谢您的帮助和时间!

回答by José Barbosa

You have your answer here: http://jsfiddle.net/kY98p/10/

你在这里有你的答案:http: //jsfiddle.net/kY98p/10/

I changed the html to use the tags thead and tfoot for header and footer

我更改了 html 以使用标签 thead 和 tfoot 作为页眉和页脚

Its just a cycle over the lines where you get the quantity and price and update the amount...

它只是一个循环,您可以在其中获取数量和价格并更新金额...

Here is the function that you should call:

这是您应该调用的函数:

function update_amounts()
{
    var sum = 0.0;
    $('#myTable > tbody  > tr').each(function() {
        var qty = $(this).find('option:selected').val();
        var price = $(this).find('.price').val();
        var amount = (qty*price)
        sum+=amount;
        $(this).find('.amount').text(''+amount);
    });
    //just update the total to sum  
    $('.total').text(sum);
}

And the event that you need is:

您需要的事件是:

$('.qty').change(function() {
    update_amounts();
});

UPDATE: jsfiddle with total: http://jsfiddle.net/kY98p/11/

更新:jsfiddle 总计:http: //jsfiddle.net/kY98p/11/

回答by Tushar Gupta - curioustushar

Fiddle Demo

Fiddle Demo

$(document).ready(function () {
    var amt = $('.amount:gt(0)'), //select element with class greater than one
        tot = $('#total'); // cache selectors
    function calculator() {
        amt.text(function () { // set text of class amount elements
            var tr = $(this).closest('tr'); // get tr
            var qty = tr.find('.qty').val(); // find it in current tr and get value of element with class qty
            var price = tr.find('.price').val(); //get price 
            return parseFloat(qty) * parseFloat(price); // return product
        });
        tot.text(function () {  //get total
            var sum = 0; //set sum = 0
            amt.each(function () { //run through all element with class amount
                sum += parseFloat($(this).text()); // add text to sum
            });
            return sum;  //set sum to total
        });
    }
    calculator(); //call the above function
    $('.qty,.price').change(calculator);// run calculator function when element with class qty or price is changed
});

回答by Farkhat Mikhalko

You can try this one (I changed your html template). Solution work as you want: 1. Calculate each row (find closest input and get data from it) 2. Calculate total and put to span 3. If you will add more selected(with my work class) it will be work

你可以试试这个(我改变了你的 html 模板)。解决方案按您的需要工作: 1. 计算每一行(找到最接近的输入并从中获取数据) 2. 计算总数并放入跨度 3. 如果您将添加更多选定的(使用我的工作类),它将起作用

$(".work").on("change", function(){
      var total = 0;
      $(".work").each(function(){
          var val = $(this).closest("tr").find("input[type='text']").val();
          total = total + ($(this).val()*val || 0);
      });
      $(".total").text(total);
    });

And html

和 html

<table>
  <tbody>
    <tr>
      <th>Product name</th>
      <th>Qty</th>
      <th>Price</th>
      <th align="center"><span id="amount" class="amount">Amount</span></th>
    </tr>
    <tr>
       <td>Product 1</td>
       <td>
         <select value="" class="qty work" name="qty">
           <option value="1">1</option>
           <option value="2">2</option>
         </select>
        </td>
        <td><input type="text" value="11.60" class="price"></td>
        <td align="center"><span id="amount" class="amount">0</span> eur</td></tr>
     <tr>
       <td>Product 2</td><td>
         <select value="" class="qty work" name="qty">
           <option value="1">1</option>
           <option value="2">2</option>
         </select>
       </td> 
       <td><input type="text" value="15.26" class="price"></td>
       <td align="center"><span id="amount" class="amount">0</span> eur</td></tr>
    <tr>
       <td colspan="2"></td>
       <td align="right"><span id="total" class="total">TOTAL</span> </td>
    </tr>
  </tbody>
</table>

And work demo

工作演示

回答by mr rogers

Here is a solution that works in with your fiddle (http://jsfiddle.net/kY98p/20/) with one minor DOM update. I put the header of the table in a THEAD so that you can count on the TBODY TR rows to be those with data.

这是一个适用于您的小提琴 ( http://jsfiddle.net/kY98p/20/)的解决方案,其中包含一个小的 DOM 更新。我把表的标题放在 THEAD 中,这样你就可以指望 TBODY TR 行是那些有数据的行。

Here we have functions to compute the total of each row and of the whole table. When you change a row, we recompute that row and then re compute the total. When we load the page, we recompute everything.

这里我们有函数来计算每行和整个表的总数。当您更改一行时,我们会重新计算该行,然后重新计算总数。当我们加载页面时,我们重新计算所有内容。

$(document).ready(function () {

    function computeRowTotal(row) {
        var $row = $(row)
        var qty = $row.find('.qty').val();
        var price = $row.find('.price').val();
        if (qty && price) {
            $row.find('.amount').html(qty * price);
        }
    }

    function computeTotal() {
        var total = 0.0
        $('tbody tr .amount').each(function () {
            console.log('T', $(this).text());
            total += parseFloat($(this).text());
        })
        $('tbody tr .total').html("Total: " + total);
    }

    function updateTable() {
        $('tbody tr').each(function (row) {
            computeRowTotal(this)
        });
        computeTotal(this)
    };
    $('select').bind('change', function () {
        computeRowTotal($(this).closest('tr'));
        computeTotal();
    });

    updateTable();

});