简体   繁体   中英

forEach loop does not check all the items in the array if a condition is met in any of them

I have a forEach loop for an array but with an if statement to check if the input is empty. The problem is that the loop stops if it finds an empty input i want it to check all the element in the array even if 1 is empty

here is my code

function showError(input, message) {
  const formControl = input.parentElement;
  formControl.className = "form-control error";
  const small = formControl.document.querySelector("small");
  small.inerText = message;
}
//show success message
function showSuccess(input) {
  const formControl = input.parentElement;
  formControl.className = "form-control success";
}

//check requiered fields

function checkRequired(inputArr) {
  inputArr.forEach(function(input) {

    if (input.value.trim() === "") {
      showError(input, "is required");
    } else {
      showSuccess(input);
    }
  });
}

// Event listener
form.addEventListener("submit", function(e) {
  e.preventDefault();
  checkRequired([username, email, password, password2]);
});

在此处输入图像描述]

you misspelled innerText as inerText(so as your submit button name). start from there. there are many places in your code where an exception could happen, such as checkRequired. my suggestion is to start with

small.innerText = message;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM