如何禁用和启用按钮,直到电子邮件有效

时间:2016-11-14 15:52:54

标签: jquery html

我已禁用该按钮,并希望在电子邮件的格式正确时启用该按钮。 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);
   }
});

1 个答案:

答案 0 :(得分:1)

您的代码运行正常,但是您在测试函数调用中输错了emailaddress。

在javascript中更改此内容: emailaddress to emailAddress

if( testEmail.test(emailaddress) ) { 

if( testEmail.test(emailAddress) ) { 

&#13;
&#13;
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);
   }
});
&#13;
<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>
&#13;
&#13;
&#13;