简体   繁体   中英

AJAX: Disabling submit button until username field is filled with email

My login page have three things:

  1. Field for the username
  2. Field for the password
  3. Submit button

This code will disable the submit button if the username field is not empty.

I want to disable the submit button until the username field is filled with a email.

Additionally, After wrote something in the username field and clear it, the submit button does not disable itself. I want the submit button to disable itself after clearing the username field.

$(':input[type="submit"]').prop('disabled', true);
 $('input[type="email"]').keyup(function() {
    if($(this).val() != '<!-- not sure what to put here -->') {
       $(':input[type="submit"]').prop('disabled', false);
    }
 });

A pure js solution for this would be:

 document.querySelector("input[type=email]").onkeyup = function(){ let reg = /^([A-Za-z0-9_\\-\\.])+\\@([A-Za-z0-9_\\-\\.])+\\.([A-Za-z]{2,4})$/; (this.value.length==0 || reg.test(this.value)==false)?document.querySelector("input[type=submit]").setAttribute("disabled","disabled"):document.querySelector("input[type=submit]").removeAttribute("disabled") } 
 <form> <input type="email"> <input type="password"> <input type="submit" disabled> </form> 

This checks the length of the input value or the input pattern whenever a key is released. If the length is zero or the pattern does not match, then it sets the disabled attribute to disabled. If not, it removes the attribute disabled altogether.

You can use RegEx to validate email. You have to disable the button if the condition is false like the following way:

 let button = $(':input[type="submit"]'); button.prop('disabled', true); $('input[type="email"]').keyup(function() { if(validateEmail($(this).val())) { button.prop('disabled', false); } else{ button.prop('disabled', true); } }); function validateEmail(email) { var re = /^(([^<>()\\[\\]\\\\.,;:\\s@"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@"]+)*)|(".+"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/; return re.test(String(email).toLowerCase()); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="email"/> <input type="submit" value="Submit"/> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM