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.