Ad Code

Automatically calculate total value using jQuery And Add more rows

<script>
// JavaScript + jQuery 2.2.4
$(function() {
    // register listener
    $('.form-control').on("change.add", calculateSum);

    // initial calculation
    calculateSum();

    // button for adding new row
    $(".addmore").click(function() {
        $('.form-control').off("change.add");
        addRow();
        $('.form-control').on("change.add", calculateSum);
        calculateSum();
    });

    // button for remove last row
    $(".delete").click(function() {
        deleteRow();
        calculateSum();
    });

    function calculateSum(){
        var total = 0;

        $('.form-control').each(function() {
            if( $(this).val() != '' )
                total += parseInt($(this).val());
        });

        $('#totalvalue').html(total);
    }

    /*    ** ONLY DEMO HELPER BELOW    */
    function addRow(){
        $("<tr>" +
             "<td><input type='checkbox' class='case'/></td>" +
             "<td><span>N.</span></td>" +
             "<td><input class='form-control' type='text' id='txt_jobid' name='txt_jobid[]'/></td>" +
             "<td><input class='form-control' type='text' id='txt_quantity' name='txt_quantity[]'/></td>" +
             "<td><input class='form-control' type='text' id='txt_price' name='txt_price[]'/></td>" +
             "<td><input class='form-control' type='text' id='txt_totalprice' name='txt_totalprice[]'/> </td>" +
           "</tr>").insertAfter("tr:last-child");
    }

    function deleteRow(){
        if( $("tr").length > 2 )
            $("tr:last-child").remove();
    }
});
</script>
<h2 style="text-align:center;">INVOICE</h2>       
  <form id='students' method='post' name='students' action='index.php'>
    <div class="table-responsive">
      <table class="table table-bordered">
        <tr>
          <th><input class='check_all' type='checkbox' onclick="select_all()"/></th>
          <th>S. No</th>
          <th>Job ID</th>
          <th>Quantity</th>
          <th>Price</th>
          <th>Total Price</th>
        </tr>
        <tr>
          <td><input type='checkbox' class='case'/></td>
          <td><span id='snum'>1.</span></td>
          <td><input class="form-control" type='text' id='txt_jobid' name='txt_jobid[]'/></td>
          <td><input class="form-control" type='text' id='txt_quantity' name='txt_quantity[]'/></td>
          <td><input class="form-control" type='text' id='txt_price' name='txt_price[]'/></td>
          <td><input class="form-control" type='text' id='txt_totalprice' name='txt_totalprice[]'/> </td>
        </tr>
      </table>
      <button type="button" class='btn btn-danger delete'>- Delete</button>
      <button type="button" class='btn btn-success addmore'>+ Add More</button>
    </div>
  </form>
  Total: <div id="totalvalue">0</div>






Full working example of your code: https://jsfiddle.net/0zpkow5L/8/

Post a Comment

0 Comments