Riya Shah
Riya Shah

Reputation: 167

Enable Disabled Button if Input is not empty

I have one simple form which have two fields called first name with id fname and email field with email. I have submit button with id called submit-btn. I have disabled submit button using javascript like this

document.getElementById("submit-btn").disabled = true;

Now I am looking for allow submit if both of my fields are filled.

My full javascript is like this

<script type="text/javascript">
  
   document.getElementById("submit-btn").disabled = true;

   document.getElementById("submit-btn").onclick = function(){
   window.open("https://google.com",'_blank');
}
  
</script>

I am learning javascript and does not know how I can do it. Let me know if someone here can help me for same. Thanks!

Upvotes: 1

Views: 1481

Answers (2)

AbsoluteBeginner
AbsoluteBeginner

Reputation: 2255

This is the simplest solution I can imagine:

myForm.oninput = () => {
  btn.disabled = fname.value == '' || email.value == '' || !email.checkValidity();
}
<form id="myForm">
  <input type="text" name="" id="fname">
  <input type="email" name="" id="email">
  <input type="submit" id="btn" value="Submit" disabled>
</form>

Personally, I prefer to use regex to check the e-mail, instead of checkValidity(). Something like this:

/^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/.test(email.value);

Upvotes: 0

yunzen
yunzen

Reputation: 33449

Id propose something like this

  1. Use a block, which encapsulates the names of variables and functions inside the block scope
  2. Make small functions, which do just one thing
  3. Prefer addEventListener over onclick or onanything
  4. There are two types of events you could use on the inputs: input and change. input will react on every keystroke, check will only react, if you blur the input element
  5. I added a check for validity to the email field with checkValidity method
    {
      const btn = document.getElementById("submit-btn");
      const fname = document.getElementById("fname");
      const email = document.getElementById("email");
      deactivate()
      
      function activate() {
        btn.disabled = false;
      }
      
      function deactivate() {
        btn.disabled = true;
      }
    
      function check() {
        if (fname.value != '' && email.value != '' && email.checkValidity()) {
          activate()
        } else {
          deactivate()
        }
      }
      
      btn.addEventListener('click', function(e) {
        alert('submit')
      })
      
      
      fname.addEventListener('input', check)
      email.addEventListener('input', check)
      
    }
    <form>
      <input type="text" name="" id="fname">
      <input type="email" name="" id="email">
      <input type="submit" id="submit-btn" value="Submit">
    </form>

Upvotes: 2

Related Questions