Skip to content
Advertisement

How to auto sum dynamic input fields in javascript

I’m trying to make an auto sum.

I’m starting with a text input field and a button. Pushing the button ads a new input field. Sum field should get … the sum. I have troubles adding the values in javascipt.

Thanks!

var counter = 1;
sum.value= number0.value;
function addNumber(divName){          
      var newdiv = document.createElement('div');
      newdiv.innerHTML = "<input type='text' name='number" + counter + "'>";
      document.getElementById(divName).appendChild(newdiv);
      sum.value += document.getElementById("number' + counter + '").value;
      nr++;          
 }

...

<div id="field"> Add value: <input type="button" value="add" onClick="addNumber('total');"><br>
<div id="total"><input type="text" name="number0"></div>

<input type="text" name="sum" id="sum">

Advertisement

Answer

I think this is what you are trying to do:

var counter = 1;

function addNumber(divName){    
  var sum = document.getElementById('sum');
  var newdiv = document.createElement('div');
  newdiv.innerHTML = "<input type='text' name='number" + counter + "'>";
  document.getElementById(divName).appendChild(newdiv);
  sum.value = getSum(counter);
  counter++;              
 }

 function getSum(numberOfDivs) {
   var sum = 0;
   for (var i=0 ; i<numberOfDivs; i++) {
     sum += parseInt(document.getElementsByName('number' + i)[0].value);
   }
   return sum;
 }

Check this plunk: http://plnkr.co/edit/5UE6YyDWmaHq5ZvVY542

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement