So I have 3 input boxes in HTML
<input type="number" id="geoOnePercentage" placeholder="Geo 1 Percentage" />
<input type="number" id="geoTwoPercentage" placeholder="Geo 2 Percentage" />
<input type="number" id="geoThreePercentage" placeholder="Geo 3 Percentage" />
What I want to do is that as the user types into these input boxes keep checking If their total exceeds the value of 100, as soon as the user types a value that makes the total exceed 100 reset the form.
For example, the user typed 50 in the first input box, that's okay.
Then the user typed 40 in the next input box, that's okay as well,
BUT THEN If the user types a value such as 15 which makes the total of all the input boxes' values combined exceed, then reset the values of all 3 input boxes.
However, I have no idea how to do this. I have learned a bit about onkeydown event thing in JavaScript but It's not working as I expected.
If someone were to shed some light on how this could be done, I would really appreciate it.
let inputs = [...document.querySelectorAll('input[type="number"]')];
inputs.forEach(inp => inp.addEventListener('input', function() {
const total = inputs.reduce((acc, inp) => acc + Number(inp.value), 0);
if (total > 100) {
inputs.forEach(inp => inp.value = '');
}
}))
<input type="number" id="geoOnePercentage" placeholder="Geo 1 Percentage" />
<input type="number" id="geoTwoPercentage" placeholder="Geo 2 Percentage" />
<input type="number" id="geoThreePercentage" placeholder="Geo 3 Percentage" />