chitoiu daniel
chitoiu daniel

Reputation: 107

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

Upvotes: 0

Views: 4480

Answers (2)

Christopher Esbrandt
Christopher Esbrandt

Reputation: 1198

Note: Explanation of the code is after the snippet.

Here's a rewrite of your code that accounts for NaN results and updates as the fields are changed (not only when the "Add" button is clicked). It also dynamically generates the first field, too. ;)

window.onload = function() {
    var counter = 0, sum = document.getElementById('sum');
    document.getElementById('add').addEventListener('click', function() {
        counter += addNumber(counter, sum);
    });
    counter += addNumber(counter, sum);
};

function addNumber(counter, sum) {
    calculateSum(sum);
    var newdiv = document.createElement('div');
    newdiv.innerHTML = '<input type="text" name="number' + counter + '" class="number" />';
    newdiv.addEventListener('keyup', function() {
        calculateSum(sum);
    });
    sum.parentNode.insertBefore(newdiv, sum);
    return 1;
}

function calculateSum(sum) {
    sum.value = 0;
    var divs = document.getElementsByClassName('number');
    for(var i = 0; i < divs.length; i++) {
        sum.value = (isNaN(parseInt(sum.value)) ? 0 : parseInt(sum.value)) + (isNaN(parseInt(divs[i].value)) ? 0 : parseInt(divs[i].value));
    }
}
<div id="field">
    Add value: <input type="button" value="add" id="add" />
    <br />
    <input type="text" name="sum" id="sum" />
</div>

It's pure JavaScript and is set-up to run without needing to call the functions from within the HTML.

Simply put, I separated the addNumber() into two functions. One to add a new field and the other to determine the total sum.

The addNumber() adds a new number field, applies an EventListener to the added fields to execute the calculatSum() whenever the browser recognizes a keyup event, and returns a value of 1 which is then added to the counter variable.

The calculateSum() zeros the sum and recalculates using the .number I added to the generated input fields. It is NaN-safe. Basically, this means the values that are ran through parseInt() are then checked that they are numbers. If parseInt() fails, it reports the value as Not a Number, or NaN. The function forces it to report a value of 0 instead of NaN.

To top it off, the script starts by defining the counter variable as 0, adding an EventListener for whenever the "Add" button gets clicked, and executes the addNumber() to place the first number field.

Upvotes: 1

lex82
lex82

Reputation: 11317

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

Upvotes: 1

Related Questions