skip to Main Content

I have 4 inputs in my form and select them with querySelectorAll. I want to check if the value of all inputs is not empty, how can I do it in an efficient way?

what I did:

const inputs = document.querySelectorAll('.input'):
if (inputs[0,1,2,3].value !== '') {
        alert('submit');
        form.reset();
    }

2

Answers


  1. You can turn the list of nodes into an array, and then use .every():

    const allFilled = Array.from(document.querySelectorAll(".input"))
      .every(input => input.value !== "");
    

    Your attempt: inputs[0,1,2,3].value will not work; JavaScript does not provide the implied facility. Instead, inputs[0,1,2,3] ends up being exactly the same as inputs[3], because the commas are parsed as the "comma operator", which is an expression separator. The first three expressions are evaluated but the values are ignored; the overall result is simply 3.

    Login or Signup to reply.
  2. inputs[0,1,2,3] is not the way how you access each element in the array. You need to go every index to obtain the value from the array.

    Solution:

    const inputs = document.querySelectorAll('.input');
    
    // converting NodeList to array as .some works with the `Array`
    const inputsArray = [...inputs];
    
    const anyEmptyInput = inputsArray.some(input => input.value === '');
    
    if(!anyEmptyInput){
      alert('submit');
      form.reset();
    }
    <input type='text' class='input' />
    <input type='text' class='input' />
    <input type='text' class='input' />
    <input type='text' class='input' />

    You can try giving the values to these inputs and check the result.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search