Validate fields with querySelectorAll

Hello Friends just one quick beginners question, When i try to input all fields
and send data, i want to make sure all fields are fill in, but with queryselectorAll I’m not able to do so, it does some weird things and validates sometimes and sometimes it wont.

i know i can do individually and give each field an id or class or even its own function for each input field.

but i wanted to do it all at the same time, with querySelectorAll and apply this line of code, im grabbing all input fields with the parent container.

var inputs = document.querySelectorAll(".container input[type=text]");

its theres a way i can do it ? or im doing something wrong in my code.
Note: console will show to see if all input fields are fill in or not, in order to pass the form

You’re looping over inputs and for each you’re logging its status. If you want to keep for loop then you should instead set a boolean that changes accordingly and check that boolean after the for loop:

  let isAllFilled = false;

  for (var i = 0; i < inputs.length; i++) {
    if (inputs[i].value === "" || inputs[i].value === null) {
      isAllFilled = false;
    } else {
      isAllFilled = true;
    }
  }

  console.log(isAllFilled);
};

Or you could use array .every() method:

const isAllFilled = [...inputs].every(input => input.value.trim())

console.log(isAllFilled)
1 Like

Hi @jenovs

Thank you so much for the reply, yes I think my mistake I was looping all of them, without a Boolean that it’s checking on them. Yes also it’s good to use the spread operation with for each. Thank so much for your help. I appreciate it. Now I know that other way of looping without doing each input field. Thank you so much!!!