How to check if field1 or field2 (or both) contains "n" and input the letter n in field3 (if condition). Otherwise (else condition) calculate.
So i setup that code. It doesn't run for the if condition, its always using the else condition. I guess their is a mistake in my if condition. How to make it work?
function findTotal() {
var arr = document.getElementById('field1');
var inputa = document.getElementById('field2');
var tot = 0;
if (inputa == "n" || arr == "n") {
document.getElementById('field3').value = "n";
} else {
for (var i = 0; i < arr.length; i ) {
if (parseFloat(arr[i].value))
tot = parseFloat(inputa[i].value) - parseFloat(arr[i].value);
}
document.getElementById('field3').value = tot;
}
}
<input type="text" maxlength="1" id="field1" name="field1" onblur="findTotal()" />
<input type="text" maxlength="1" id="field2" name="field2" onblur="findTotal()" />
<input type="text" maxlength="1" id="field3" name="field3" />
Here is the code to try: https://jsfiddle.net/gpbdvnso/
CodePudding user response:
There are quite a few points still unclear, but maybe the following is a pointer of where you could go? I collected all the DOM elements in a collection and then assigned the elements to the variables a
, b
and sum
(a de-structuring assignment).
function findTotal() {
const [a,b,sum] = document.querySelectorAll('input');
sum.value=a.value=="n"||b.value=="n"?"n": a.value ( b.value)
}
<input type="text" maxlength="1" id="field1" name="field1" onblur="findTotal()" />
<input type="text" maxlength="1" id="field2" name="field2" onblur="findTotal()" />
<input type="text" maxlength="1" id="field3" name="field3" />