我已禁用该按钮,并希望在电子邮件的格式正确时启用该按钮。 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);
}
});
答案 0 :(得分:1)
您的代码运行正常,但是您在测试函数调用中输错了emailaddress。
在javascript中更改此内容: emailaddress to emailAddress
if( testEmail.test(emailaddress) ) {
到
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);
}
});
&#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;