Skip to content
Advertisement

How to disable submit button until all mandatory fields are filled using html and vanilla js

How to disable submit button until the user enters all fields and also how to use event listener on submit form.

<form action='index.html' id="form-user" onsubmit="init()">
  <input type="text" name="username" id="username" placeholder="username">
  <input type="email" name="email" id="email" placeholder="email">
  <input type="password" name="password" id="password" placeholder="password">
  <button type="submit" name="submit" id='button-send'>SUBMIT</button>
</form>
const init = function () {
  let username = document.getElementById("username").value;
  let password = document.getElementById("password").value;
  let email = document.getElementById("email").value;
  alert(username,password,email)
};

Jsfiddle link

Advertisement

Answer

Set up a validation object with booleans to record if all your values have met validation.

Then I’d loop through all your inputs and add an event listener to each of them. In this example I’ve checked to see if each has at least one character in them, but you might want to expand on this.

Finally, loop through your validation object and check if all the values are true. If they are, remove the disabled attribute from the button.

let inputs = document.querySelectorAll('input');
let buttonSend = document.getElementById('button-send');

let inputValidator = {
  "username": false,
  "email": false,
  "password": false
}

inputs.forEach((input) => {
  input.addEventListener('input', () => {
    let name = event.target.getAttribute('name');
    if (event.target.value.length > 0) {
      inputValidator[name] = true;
    } else {
      inputValidator[name] = false;
    };

    let allTrue = Object.keys(inputValidator).every((item) => {
      return inputValidator[item] === true
    });

    if (allTrue) {
      buttonSend.disabled = false;
    } else {
      buttonSend.disabled = true;
    }
  })
})
<form action='index.html' id="form-user">
  <input type="text" name="username" id="username" placeholder="username">
  <input type="email" name="email" id="email" placeholder="email">
  <input type="password" name="password" id="password" placeholder="password">
  <button type="submit" name="submit" id='button-send' disabled>SUBMIT</button>
</form>
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement