jeffigy
jeffigy

Reputation: 97

Jquery Auto Calculation

Credits to the owner of the code.

How can I make the script into multiplication? the script an addition of .amount. Please help.

<tr>
  <td>
    <input type="text" class="form-control input-sm text-right amount" >
  </td> 
  <td>
    <input type="text" class="form-control input-sm text-right amount">
  </td>
  <td>
    <input type="text" class="form-control input-sm text-right" id="total_amount" readonly>
  </td>
</tr>
<script>
  $(function() {

      $('.amount').mask('#,###.##',{reverse : true});

      var total_amount = function() {
          var sum=0;
          $('.amount').each(function(){
              var num = $(this).val().replace(',','');

              if(num != 0) {
                  sum +=parseFloat(num);
              }    
          });
          $('#total_amount').val(sum.toFixed(2));
      }
       $('.amount').keyup(function(){
          total_amount();
       });
  });
</script>

Upvotes: 1

Views: 61

Answers (1)

m1k1o
m1k1o

Reputation: 2364

Identity element (or neutral element) of Multiplication operation in Real numbers is one. So your var sum = 1; will be that.

After each iteration, in your case two hardcoded, you will multiply sum with new number. Hence changing sum *=parseFloat(num).

That leaves you with the old regular multiplication.

  $(function() {

      $('.amount').mask('#,###.##',{reverse : true});

      var total_amount = function() {
          var sum=1;
          $('.amount').each(function(){
              var num = $(this).val().replace(',','');

              if(num != 0) {
                  sum *=parseFloat(num);
              }    
          });
          $('#total_amount').val(sum.toFixed(2));
      }
       $('.amount').keyup(function(){
          total_amount();
       });
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://igorescobar.github.io/jQuery-Mask-Plugin/js/jquery.mask.min.js"></script>
<tr>
  <td>
    <input type="text" class="form-control input-sm text-right amount" >
  </td> 
  <td>
    <input type="text" class="form-control input-sm text-right amount">
  </td>
  <td>
    <input type="text" class="form-control input-sm text-right" id="total_amount" readonly>
  </td>
</tr>

Upvotes: 1

Related Questions