I am trying to have 4 inputs of data input and 1 single output, for example a calculator, that two inputs are a sum and the other 2 a multiplication, and the value is received by a single input. if the first two inputs have values, the sum is executed, and if the last two inputs have values, then multiplication is executed, I leave the code.
If this is very elaborate ... could someone tell me how to do it in a more optimal way? taking into account that I put this as an example to do it as a question on the page but the idea is to make it a little bigger, something like 8 input inputs and 4 output
var input1 = document.getElementById("uno");
var input2 = document.getElementById("dos");
var input3 = document.getElementById("tres");
var input4 = document.getElementById("cuatro");
var resultado = document.getElementById("resultado");
var prueba = document.getElementById("prueba");
var suma = function(a, b) {
a = a || 0;
b = b || 0;
resultado.value = a + b;
}
var multiplicacion = function(a, b) {
a = a || 0;
b = b || 0;
resultado.value = a * b;
}
prueba.addEventListener("click", function(e) {
e.preventDefault();
if (input1.value == 0 && input2.value == 0){
multiplicacion(input3.valueAsNumber , input4.valueAsNumber);
} else {
suma (input1.valueAsNumber, input2.valueAsNumber)
}
})
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Calculadoras</title>
</head>
<body>
<input type="number" id="uno" placeholder="uno">
<input type="number" id="dos" placeholder="dos">
<input type="number" id="tres" placeholder="tres">
<input type="number" id="cuatro" placeholder="cuatro">
<input type="number" id="resultado" placeholder="resultado">
<input type="submit" value="calcular" id="prueba">
</body>
</html>
(UPDATE)
in the javascript code I was missing an important part that was to take the values and then display them in the result input, then update it. This is the way I am using the code right now, in addition to a button that cleans all the fields, what would be the most optimal way to do the operations? the true code is much longer