I'm currently working on a program that calculates the sum of 6 input values, but I've encountered an issue where if a value is missing (for example, only providing 5 values), the result becomes NaN. I attempted to address this by assigning empty values a default of 0 using a for loop and an if statement, however, it doesn't seem to be working as expected. Could someone please assist me with this?
Here's the code snippet:
document.getElementById("b").onclick = function() {
var values = new Array();
values[0] = document.getElementById("x").value;
values[1] = document.getElementById("y").value;
values[2] = document.getElementById("z").value;
values[3] = document.getElementById("a").value;
values[4] = document.getElementById("g").value;
values[5] = document.getElementById("c").value;
for (i = 0; i < values.length; i++) {
if (isNaN(values[i])) {
values[i] = 0;
}
}
var sum = parseFloat(values[0]) + parseFloat(values[1]) + parseFloat(values[2]) + parseFloat(values[3]) + parseFloat(values[4]) + parseFloat(values[5]);
document.getElementById("result").innerHTML = "The total sum is " + sum + ".";
}
<form>
<input type="number" placeholder="Value 1" id="x" required>
<input type="number" placeholder="Value 2" id="y" required>
<input type="number" placeholder="Value 3 (optional)" id="z">
<input type="number" placeholder="Value 4 (optional)" id="a">
<input type="number" placeholder="Value 5 (optional)" id="g">
<input type="number" placeholder="Value 6 (optional)" id="c">
<input type="button" class="btn btn-primary" id="b" value="Apply" />
</form>
<div id="result" class="desc"></div>
Edit: This is not a duplicate because the question that I wrote here (Why can't I do addition between 4 variables in JavaScript but I can do it with 3 variables?) is about the addition, and this one is about handling isNaN values.