1

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!

2 Answers 2

2

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>
Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.