如果条件不符合jQuery

时间:2016-12-08 01:18:11

标签: javascript jquery

我有条件,如果选中复选框并且电子邮件字段以@ xyz.edu结尾,则应启用提交按钮,如果未选中复选框且电子邮件字段包含@ xyz.edu,即使那时按钮也应该被禁用。

<div class="input-field col s12 m10 offset-m1 offset-s2">
    <input id="email" name="email" th:value="${user.email}" type="email" class="validate" />
    <label for="email">Email</label>
</div>

<div class="row">
    <div class="input-field col s12 m10 offset-m1 offset-s2">
        <input id = "checkbox" name="userRole" value="ADMIN" type="checkbox" class="validate" />
        <label>Admin</label>
    </div>
</div>

<div class="row">
    <div class="input-field col s12 m10 offset-m1 offset-s2">
        <button id="submit" class="btn waves-effect waves-light" type="submit" disabled = "disabled" name="action" value="signup">Sign Up</button>
    </div>
</div>

jQuery代码:

 $('#checkbox').click(function(){

           if(this.checked)
           {
              var email = $('#email').val();
              var str = "@sjsu.edu"
              if(email.match("@sjsu.edu$"))
              {

                $("#submit").removeAttr("disabled");
              }
              else
              {
                $("#submit").attr("disabled", "disabled");
              }
           }
    });

因此,当我将输入设为@ gmail.com并选中复选框时,按钮仍处于禁用状态。现在,如果我再次更改输入字段,即使条件不满足,它也会启用该按钮。有人可以帮助我

这是我的代码链接:https://jsfiddle.net/chandham/e5g0m7o9/

2 个答案:

答案 0 :(得分:0)

将验证代码提取到单独的函数 - 即检查#checkbox已检查且#email以@ sjsu.edu结尾的代码。然后将此函数绑定到事件处理程序以获取复选框和电子邮件的更改事件,如下所示:

$("#email, #checkbox").change(updateSubmitButtonState);

function updateSubmitButtonState() {
    // Code to validate inputs
}

修改:Working JS Fiddle

我还为页面加载事件添加了一个事件处理程序,因此它以正确的状态启动。

答案 1 :(得分:0)

试试这个例子:

&#13;
&#13;
$(function() {
  $('#checkbox,#email').on('input', function(e) {
    var checked = $('#checkbox').is(':checked');
    var endsWith = /@xyz\.edu$/.test($('#email').val());
    $('#submit').prop('disabled', !((!checked && !endsWith) || (checked && endsWith)));
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="input-field col s12 m10 offset-m1 offset-s2">
  <input id="email" name="email" value="abc@xyz.edu" type="email" class="validate" />
  <label for="email">Email</label>
</div>

<div class="row">
  <div class="input-field col s12 m10 offset-m1 offset-s2">
    <input id="checkbox" name="userRole" value="ADMIN" type="checkbox" class="validate" />
    <label>Admin</label>
  </div>
</div>

<div class="row">
  <div class="input-field col s12 m10 offset-m1 offset-s2">
    <button id="submit" class="btn waves-effect waves-light" type="submit" disabled="disabled" name="action" value="signup">Sign Up</button>
  </div>
</div>
&#13;
&#13;
&#13;