Home > Software design >  Here is my login form How Do I disable submit button if the input field is empty?
Here is my login form How Do I disable submit button if the input field is empty?

Time:06-20

Here is my login form How Do I disable submit button if the input field is empty ?

This is my login page.

submit button works if the input field is empty

<div >
  <form action="/login" method="POST">
    <h1>Login</h1>
    <!-- input fields start from here -->
    <div >
      <div >
        <input type="email" id="email" placeholder="Email" autocomplete="nope" name="email">
      </div>
      <div >
        <input type="password" id="password" placeholder="Password" autocomplete="new-password" name="password">
      </div>    
<!-- Action links -->
      <a href="#" >Forgot Your Password?</a>
      <br>
      <a href="register" >Create an Account</a>
    </div>
<!-- submit buttons -->
    <div >
      <button type="submit" >Sign in</button>
    </div>
  </form>
</div>

CodePudding user response:

Add the required attribute to each <input>. If any <input> is empty and the submit event is triggered, the submitting process will be stopped and a hint will popup to notify the user of an empty <input> needing data. See Example A.

If you really want the button disabled then see Example B, details are commented in the example.

Example A

<form>
  <input required>
  <button>Submit</button>
</form>

Example B

// Bind the first <form> to the input event
document.forms[0].oninput = enableButton;

function enableButton(e) {
  // Reference all form controls
  const IO = this.elements;
  // Collect all [name='data'] into an array
  const inputs = [...IO.data];
  
  /*
  If every input has at least 1 character as .value...
  ...enable the button...
  ...otherwise disable the button
  */
  if (inputs.every(input => input.value.length > 0)) {
    IO.btn.disabled = false;
  } else {
    IO.btn.disabled = true;
  }
}
<form>
  <input name='data'>
  <input name='data'><br>
  <button id='btn' disabled>Submit</button>
</form>

  •  Tags:  
  • html
  • Related