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>
0

2 Answers 2

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.

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

1 Comment

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.
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;
   }
});

Comments

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.