validationform-submitdisabled-controlsubmit-buttondisable

Disabling Submit button until required fields are filled using JavaScript


I am trying to disable the form Submit button until the required fields are filled. However my code does not seem to be looping properly through the condition as any input enables the submit button. https://codepen.io/ldanneman/pen/MWyGJMx?editors=0010

<form>
    <div class="form-box">
        <label for="fname">First Name<span>*</span></label>
        <input type="text" id="fname" name="First Name" placeholder="First Name" required><br>
        <label for="lname">Last Name</label>
        <input type="text" id="lname" name="Last Name" placeholder="Last Name"><br>
        <label for="email">Email<span>*</span></label>
        <input type="email" id="email" name="Email" placeholder="abc@client.com" required><br>
        <label for="phone">Phone<span>*</span></label>
        <input type="tel" id="phone" name="Phone" placeholder="111-222-3333" required><br>
        <label for="comments">Comments<span>*</span></label>
        <textarea id="comments" name="comments"  placeholder="Comments" required></textarea><br>
    
      <button class="submit" type="submit">Submit</button>

    </div>
    
    
</form>
</div>

JavaScript:

let requiredInputs = document.querySelectorAll("[required]");
let submitButton = document.querySelector(".submit");

submitButton.disabled = true;

for(let i = 0; i < requiredInputs.length; i++){
requiredInputs[i].addEventListener("input", buttonState)
};

function buttonState() {
  if (requiredInputs.value === "") {
    submitButton.disabled = true;
  } else {
    submitButton.disabled = false;
  }
}


Solution

  • You're close, but the code in your callback, buttonState() is insufficient to accomplish what you want. It is checking for the value of requiredInputs which is a collection of HTML Input elements. What you want to do is loop through each item in that collection and check if their value is set:

    function buttonState() {
      submitButton.disabled = Array.from(requiredInputs).some(x => x.value === '');
    }
    

    The code above will use some() which will returns true if any callback results in true, in the case if the value of an input is an empty string.