Dealing with a summing function for input field numbers to a single digit, I face the challenge of applying it to two separate fields upon clicking an HTML button. Rather than duplicating the function, is there a more efficient approach to achieve this?
function getSum1() {
const input = document.getElementById('dateInput1').value;
var sum = 0;
for (var i = 0; i < input.length; i++) {
const num = parseInt(input.charAt(i));
if (!isNaN(num)) {
sum += num;
}
}
const total = (sum - 1) % 9 + 1;
document.getElementById("result1").textContent = "Your number is: " + total;
}
function getSum2() {
const input = document.getElementById('dateInput2').value;
var sum = 0;
for (var i = 0; i < input.length; i++) {
const num = parseInt(input.charAt(i));
if (!isNaN(num)) {
sum += num;
}
}
const total = (sum - 1) % 9 + 1;
document.getElementById("result2").textContent = "Your number is: " + total;
}
<div class="container">
<div class="cell-1"><input type="text" id="dateInput1"></div>
<div class="cell-2"><img src="file:///Users/Nineborn/Downloads/My%20Post.png" alt=""></div>
<div class="cell-3"><input type="text" id="dateInput2"></div>
<div class="cell-4" id="result1"></div>
<div class="cell-5"><button onclick="getSum1(); getSum2()">Calculate</button></div>
<div class="cell-6" id="result2"></div>
<div class="cell-7"></div>
<div class="cell-8"></div>
<div class="cell-9"></div>
</div>