• Home
  • Jobs
  • Courses
  • Teachers
  • For business
  • Blog
  • ES/EN

0

26
Views
Find sum of automatically generated input fields value

I have a button that when you click it appends an input fields in a div, this values comes from ajax request.

 var i = 0;

 $(document).on('click', '#add-btn', function() {
     ++i;
           var user = $('#productName').attr('value');
           var price = $('#price').attr('value');    
      $.ajax({    //create an ajax request to display.php
        type: "GET",
        url: "getPrice.php", 
        data: {user:user, price:price},            
        dataType: "html",   //expect html to be returned                
        success: function(response){                    
          $("#dynamicAddRemove").append('<tr style="height:5em;" id="tr"><td><input name="productName['+i+']" readonly class="form-control" type="text" value="'+user+'"/></td><td><div class="quantit buttons_added"><input class="form-control quantity" id="number"  type="number" name="qty[' + i + ']" value="1"/></div></td><td><input  class="form-control amount" type="text" readonly value="'+price+'" name="price[' +i +']"/></td><td class="td"><input type="text" value="'+price+'" name="subTotal['+i+']" placeholder="Subtotal" class="form-control subtotal" id="grandTotal" readonly/><td><button type="button" name="add" class="btn btn-danger remove-tr">-</button></td>');  
        }

    });
});

after appending the input fields now i want to add every value of the subTotal to get grandTotal.

     var iSum = 0;
   $(document).on('mouseout', '.amount , .quantity, #addvalue', function() {
    iSum = 0;
       $('input[name="subTotal[]"]').each(function(){
        var LiSum =parseInt($('input[name="subTotal[]"]').val());
        if(LiSum != undefined || LiSum != ''){
            iSum+=LiSum;
        }
       
       });
       $('#sum').html(iSum);
       alert(iSum);
    });

after successfully appending values, i keep on getting 0 as grandTotal

16 days ago ·

Santiago Trujillo

1 answers
Answer question

0

Replace $('input[name="subTotal[]"]') by $('input[name^="subTotal"]'). This will find all input fields with names starting with "subTotal". The name "subTotal[]" you were originally looking for does not appear anywhere in your markup.

16 days ago · Santiago Trujillo Report
Answer question
Find remote jobs
Loading

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2022 PeakU Inc. All Rights Reserved.