0

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">
2
  • 1
    Values will always come back as strings so you will need to parseInt($(input).value) before adding. It appears you're using .= instead of += in your sum logic. That will fail, I think thats only for concatenation in PHP..
    – Brant
    Commented Nov 16, 2015 at 19:14
  • @Brant You are right with "+=". How should the parseInt($(input).value) be in my case, because i think i get stuck in quotes? Commented Nov 16, 2015 at 22:14

2 Answers 2

1

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

1

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.