Quantcast
Channel: Active questions tagged html - Stack Overflow
Viewing all articles
Browse latest Browse all 72388

Form Input number onchange

$
0
0

As shown in the code below, I want to change the value of the input "total" to the sum of two inputs dynamically as I click on the button that add value to "val1". I don't want to add this event on the button as onclick, cuz at the end will be several fields that will sum the total and they will change without a button.

Actually I wanted that the value of "total" start with this sum too, I didn't want to input already the value 8.

As sugest by @tallberg, follows bellow:

function addVal(index) {
  if (document.getElementById(index).value < 20) {
    document.getElementById(index).value = Number(document.getElementById(index).value) + 1;
    calcSum();
  }
}

var ValueElements = document.getElementsByClassName('Value');
var TotalElement = document.getElementById('total');
for (var i of ValueElement) {
  i.addEventListener('keyup', calcSum)
}

function calcSum() {
  var sum = 0;
  for (var i of ValueElements) {
    sum += parseInt(i.value) || 0;
  }
  TotalElement.value = sum;
}
<td><input type="number" class="Value" name="VAL1" id="val1" value="8" min="8" max="20" readonly="true"><button type="button" id="btAddVal" onclick="addVal('val1');"><img src="img/icons/mais.png"> </button></td><td><input type="number" class="Value" name="VAL2" id="val2" value="0" readonly="true"></td><td><input type="number" name="TOTAL" id="total" readonly="true" value="8"></td>

Viewing all articles
Browse latest Browse all 72388

Trending Articles