1

How do I modify this to get the sum value? I have tested this code can be sum when the textbox is fixed in HTML will auto sum. but it can't be auto sum with a dynamic input box. what I have missed?

One more question - how to minus value when user removes the row

Here is for test Auto Sum with dynamic add input box Jsfillder

JavaScript

//this is dynamic add input box

$(document).ready(function () {
  var max_fields = 10; //maximum input boxes allowed
  var wrapper = $(".input_fields_wrap"); //Fields wrapper
  var add_button = $(".add_field_button"); //Add button ID

  var x = 1; //initlal text box count
  $(add_button).click(function (e) { //on add input button click
    e.preventDefault();
    if (x < max_fields) { //max input box allowed
      x++; //text box increment
      //$(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="remove_field">Remove</a></div>'); //add input box
      $(wrapper).append('<div class="col-lg-12 product_wrapper">' +

                        '<div class="col-lg-3" >' +
                        '<label>Product</label>' +
                        '<textarea type="text" class="product_textarea" name="Product[]"></textarea>' +
                        '</div>' +

                        '<div class="col-lg-6">' +
                        '<label>Description</label>' +
                        '<textarea class="description_textarea" name="ProductDescription[]" style=""></textarea>' +
                        '</div>'+

                        '<div class="col-lg-2 form-group">' +
                        '<label>Price</label>' +
                        '<input type="text" class="price_tag form-control" name="Price[]"/>' +                                                
                        '</div>' +

                        '<a href="#" class="remove_field btn btn-danger pull-right">cancel</a>' +

                        '</div>'                                       );
    }
  });

  $(wrapper).on("click", ".remove_field", function (e) { //user click on remove text
    e.preventDefault(); $(this).parent('.product_wrapper').remove(); x--;
  })     

  //here is my calculate function    

  //Iterate through each Textbox and add keyup event handler
  $(".price_tag").each(function () {
    $(this).keyup(function (e) {
      e.preventDefault();
      //Initialize total to 0
      var total = 0;
      $(".price_tag").each(function () {
        // Sum only if the text entered is number and greater than 0
        if (!isNaN(this.value) && this.value.length != 0) {
          total += parseFloat(this.value);
        }
      });
      //Assign the total to label
      //.toFixed() method will roundoff the final sum to 2 decimal places
      $('#total').val(total.toFixed(2));
    });
  });

});

HTML

<div class="input_fields_wrap"></div>

<button class="add_field_button btn btn-primary pull-right">Add More Fields</button>

<div>total</div>
<div><input class="total" id="total"type="text" name="txt"/></div>

1 Answer 1

4

You attach your event lister before the actual elements are present. Use .on() instead: http://api.jquery.com/on/

This will create a listener that will check each time that you're pressed a button on '.price_tag', even if you don't have elements with class='price_tag' in your document yet:

$("body").on('keyup', '.price_tag', function (e)

Working example:

$(document).ready(function() {
  var max_fields = 10; //maximum input boxes allowed
  var wrapper = $(".input_fields_wrap"); //Fields wrapper
  var add_button = $(".add_field_button"); //Add button ID

  var x = 1; //initlal text box count
  $(add_button).click(function(e) { //on add input button click
    e.preventDefault();
    if (x < max_fields) { //max input box allowed
      x++; //text box increment
      //$(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="remove_field">Remove</a></div>'); //add input box
      $(wrapper).append('<div class="col-lg-12 product_wrapper">' +

        '<div class="col-lg-3" >' +
        '<label>Product</label>' +
        '<textarea type="text" class="product_textarea" name="Product[]"></textarea>' +
        '</div>' +

        '<div class="col-lg-6">' +
        '<label>Description</label>' +
        '<textarea class="description_textarea" name="ProductDescription[]" style=""></textarea>' +
        '</div>' +

        '<div class="col-lg-2 form-group">' +
        '<label>Price</label>' +
        '<input type="text" class="price_tag form-control" name="Price[]"/>' +
        '</div>' +

        '<a href="#" class="remove_field btn btn-danger pull-right">cancel</a>' +

        '</div>');
    }
  });

  $(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
    e.preventDefault();
    $(this).parent('.product_wrapper').remove();
    calculateTotal();
    x--;
  })

  function calculateTotal() {
    //Initialize total to 0
    var total = 0;
    $(".price_tag").each(function() {
      // Sum only if the text entered is number and greater than 0
      if (!isNaN(this.value) && this.value.length != 0) {
        total += parseFloat(this.value);
      }
    });
    //Assign the total to label
    //.toFixed() method will roundoff the final sum to 2 decimal places
    $('#total').val(total.toFixed(2));
  }

  //Iterate through each Textbox and add keyup event handler
  $("body").on('keyup', '.price_tag', function(e) {

    e.preventDefault();
    calculateTotal();

  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="input_fields_wrap"></div>

<button class="add_field_button btn btn-primary pull-right">Add More Fields</button>

<div>total</div>
<div>
  <input class="total" id="total" type="text" name="txt" />
</div>

Sign up to request clarification or add additional context in comments.

2 Comments

thx!! it works, but how do I enhance it to make it when user remove 1 of the dynamic textbox and update the sum value?
You can extract calculateTotal() to a function and call it from both places.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.