0

I have tried to find out the summation of multiple rows of jquery forms. But could not.

Input :

<input type="text" name="item_quantity[]" class="form-control item_quantity" " />

Jquery

$('input').keyup(function()
{ 
   var num  = Number($('#item_quantity').val());  
   var sum = 0;
   for(i=0; i<num.size(); i++)
   {
       sum += num;
       document.getElementById('total').value = sum;
   }
});

Output :

Total: <span id="total"></span>
rashedcs
  • 3,588
  • 2
  • 39
  • 40

2 Answers2

1

You are selecting by id: $('#item_quantity'), whilst using the name attribute. Instead you should use the $('[name=item_quantity[]]') selector.

Something like this should work:

$('input').keyup(function()
{ 
   const $elements = $('[name=item_quantity[]]');
   let sum = 0;
   for (let i=0; i<$elements.size(); i++)
   {
       sum += Number($elements[i].val());
   }
   $('#total').html(sum);
});

You can checkout this answer for more information about this selector.

JohannesB
  • 1,995
  • 21
  • 35
  • 1
    Note that the `$('input')` selector is **very** general, be careful with this, because it might trigger unnecessary recalculations, when other, non-total related fields are changed. – JohannesB Jan 10 '20 at 13:23
0
$('input').keyup(function()
{ 
   var names=document.getElementsByName('item_quantity[]');
   var sum =0;
   for(key=0; key < names.length; key++)  
   {
      sum += Number(names[key].value);
      document.getElementById('total').value = sum;
   }
});
Tony Dong
  • 3,213
  • 1
  • 29
  • 32
rashedcs
  • 3,588
  • 2
  • 39
  • 40