serj serj - 25 days ago 9
HTML Question

How to disable&enable button until email is valid or not

I have disabled the button and would like to enable it when the email will be in the correct form.
HTML:

<form action="" class="form-inline">
<div class="form-group">
<label class="sr-only">Email</label>
<input type="email" id="emailaddress" class="form-control form-control-md" placeholder="john@example.com">
</div>
<button type="button" class="btn btn-outline-secondary btn-md" id="btn-subscribe">Connect</button>
</form>


JQuery:

var emailAddress;
var testEmail = /^[A-Z0-9._%+-]+@([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
$('#btn-subscribe').prop('disabled', true);


$("#emailaddress").on("keyup change", function() {
emailAddress = $(this).val();
if( testEmail.test(emailaddress) ) {
$('#btn-subscribe').prop('disabled', false);
}
});

Answer

Your code works fine, however you have mistyped emailaddress in the test function call.

Change this in the javascript: emailaddress to emailAddress

if( testEmail.test(emailaddress) ) { 

to

if( testEmail.test(emailAddress) ) { 

var emailAddress;
  var testEmail = /^[A-Z0-9._%+-]+@([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
  $('#btn-subscribe').prop('disabled', true);


$("#emailaddress").on("keyup change", function() {
   emailAddress = $(this).val();
   if( testEmail.test(emailAddress) ) { 
      $('#btn-subscribe').prop('disabled', false);
   }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" class="form-inline">
                <div class="form-group">
                    <label class="sr-only">Email</label>
                    <input type="email" id="emailaddress" class="form-control form-control-md" placeholder="john@example.com">
                </div>
                <button type="button" class="btn btn-outline-secondary btn-md" id="btn-subscribe">Connect</button>  
            </form>