I have made this code to validate if all input fields have been filled. If not submission is not allowed, but when it is correct I have to click twice on the submit button, the first time it validates and adds the eventListener and the second time it runs because it has the event listener. How can I modify the code so that I only have to click once?
function validaInput() {
const inputs = document.querySelectorAll(".input-field");
let validez;
inputs.forEach(function(input) {
if (input.value !== "") {
validez = true;
} else {
validez = false;
}
});
if (validez) {
submitBtn.addEventListener("click", calculaPromedio);
submitBtn.addEventListener("click", addMateria);
} else {
alert("No ha llenado todos los campos.");
}
}
Just call the relevant functions instead of adding a listener. (Also, you would otherwise add new duplicate listeners every time the button is clicked.)
if (validez) {
calculaPromedio();
addMateria();
} else {
alert("No ha llenado todos los campos.");
}
If you use this
inside those function, you'd need instead e.g. calculaPromedio.call(this)
.