最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin5浏览0评论

I have prepared this 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 qty select fields.. really plicated for me. I am so far stacked here:

$(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

thank you for your help and time in advance!

I have prepared this 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 qty select fields.. really plicated for me. I am so far stacked here:

$(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

thank you for your help and time in advance!

Share Improve this question edited Feb 26, 2014 at 16:44 talemyn 7,9504 gold badges32 silver badges52 bronze badges asked Feb 26, 2014 at 16:34 thecore7thecore7 4842 gold badges8 silver badges31 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 9

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

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

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/kY98p/11/

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
});

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

$(".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

<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

Here is a solution that works in with your fiddle (http://jsfiddle/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.

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

$(document).ready(function () {

    function puteRowTotal(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 puteTotal() {
        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) {
            puteRowTotal(this)
        });
        puteTotal(this)
    };
    $('select').bind('change', function () {
        puteRowTotal($(this).closest('tr'));
        puteTotal();
    });

    updateTable();

});
发布评论

评论列表(0)

  1. 暂无评论