Home > Mobile >  JS inputs.every() not evaluating to true even though both elements are true
JS inputs.every() not evaluating to true even though both elements are true

Time:08-27

I currently have two input fields email and text in my HTML code. Inside Javascript, I am attempting to do a reportValidity() for both before moving on to the next step in a multi-step form. For some reason, if I do a inputs.some(input => {console.log(input.reportValidity())}) I get the values true and true for both form inputs when appropriate.

After removing the console.log(), I am expecting the next line and const allValid to be equals to true but when i console.log(allValid) it returns false.

I have omitted some things from the JavaScript block below, but when I do a console.log() of input from inputs, it logs the correct input fields.

HTML Code

            <div >
                <label for="email">Email</label>
                <input type="email" name="email" id="email" >
            </div>
            <div >
                <label for="password">Password</label>
                <input type="password" name="password" id="password">
            </div>

JavaScript

const multiStepForm = document.querySelector("[data-multi-step]")
const formSteps = [...multiStepForm.querySelectorAll("[data-step]")]
const inputs = [...formSteps[currentStep].querySelectorAll("input")]

console.log("Each run starts here")
inputs.forEach(input => console.log(input.reportValidity()))
const allValid = inputs.every(input => {input.reportValidity()})
console.log(allValid)

When ran, inside the console my log is

This run starts here.
true x 2 <- from reportValidity()
false <- from const AllValid

CodePudding user response:

Solution was to remove a pair of {} as I was not returning anything.

JavaScript

const multiStepForm = document.querySelector("[data-multi-step]")
const formSteps = [...multiStepForm.querySelectorAll("[data-step]")]
const inputs = [...formSteps[currentStep].querySelectorAll("input")]

console.log("Each run starts here")
inputs.forEach(input => console.log(input.reportValidity()))
const allValid = inputs.every(input => input.reportValidity()) //Remove {} here
console.log(allValid)
  • Related