Skip to content
Advertisement

How to sum of table amount in javascript? [closed]

I have a table where I’m giving few amounts now I want to total of all amounts in table how can i do this?

My Code:-

   var tr = "";
        var totalAmount = "";
        var footerTr = "";
        for(var i=1; i<=31; i++){
            tr += `<tr>
                <td>${i}</td>
                <td>${i*2}</td>
                </tr>`

                totalAmount += `${i*2}+`
            }
            footerTr = `<tr>
                <th>Total</th>
                <th>${totalAmount}</th>
                </tr>`

            $('#saving_calc tbody').append(tr);
            $('#saving_calc tfoot').append(footerTr);
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.slim.min.js"></script>
 <table class="table table-bordered"id="saving_calc" >
        <thead>
            <th>Date</th>
            <th>Amount</th>
        </thead>
      <tbody>
      </tbody>
      <tfoot>
      </tfoot>
    </table>

Thanks for your efforts!

Advertisement

Answer

Like this:

        var tr = "";
        var totalAmount = "";
        var total = 0;  //this your total
        var footerTr = "";
        for(var i=1; i<=31; i++){
            tr += `<tr>
                    <td>${i}</td>
                    <td>${i*2}</td>
                   </tr>`;

                totalAmount += `${i*2}+`;
                total += i*2;  //this your total
         }
         totalAmount = totalAmount.substring(0, totalAmount.length - 1); // remove last plus
         totalAmount += '='+total;
         footerTr = `<tr>
                       <th>Total</th>
                       <th>${totalAmount}</th>
                     </tr>`;

         $('#saving_calc tbody').append(tr);
         $('#saving_calc tfoot').append(footerTr);
         console.log(total);//this your total 
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.slim.min.js"></script>
 <table class="table table-bordered"id="saving_calc" >
        <thead>
            <th>Date</th>
            <th>Amount</th>
        </thead>
      <tbody>
      </tbody>
      <tfoot>
      </tfoot>
    </table>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement