I have a few text boxes on my javascript page with the class of textID. So if I were to do
function UpdateTotals() {
getText = document.getElementsByClassName('textID').value;
}
All of the values will be numbers, so how do I add all of the values in this class together? Example: there are 4 text boxes, each one has the number 2 in it. I want to get 8 by adding them all together (but only the text boxes that are in that class).
One example could be using Array.prototype.reduce()
const textID = document.querySelectorAll('.textID');
const total = [...textID].reduce((a, el) => a + (+el.textContent.trim()), 0);
console.log(total); // 8
<div class="textID">2</div>
<div class="textID">2</div>
<div class="textID">2</div>
<div class="textID">2</div>
For INPUT elements:
const textID = document.querySelectorAll('.textID');
const total = [...textID].reduce((a, el) => a + (+el.value), 0);
console.log(total); // 8
<input class="textID" type="number" value="2">
<input class="textID" type="number" value="2">
<input class="textID" type="number" value="2">
<input class="textID" type="number" value="2">
Using NodeList.forEach()
const textID = document.querySelectorAll('.textID');
let total = 0;
textID.forEach(el => total += +el.value);
console.log(total); // 8
<input class="textID" type="number" value="2">
<input class="textID" type="number" value="2">
<input class="textID" type="number" value="2">
<input class="textID" type="number" value="2">