当输入框处于焦点状态时,禁用复选框启用

时间:2019-11-30 08:33:00

标签: javascript jquery html

当任何一个以输入字段为焦点然后禁用复选框启用时,我该怎么做?

这是我的代码(HTML):

<!DOCTYPE html>
    <html>
       <body>

          <form action="#">
          User name:<br>
          <input type="text" name="name">
          <br>
          User password:<br>
          <input type="password" id="password" name="password">

          <input type="checkbox" name="email_login_details" id="email_login_details" value="Car">Email login details

<!-- Note: I want firstly disabled this checkbox. When I type password then enable this checkbox. -->

          </form>
   </body>
</html>

jQuery:

$("#password").change(function () {
            var password = $('#password').val();
            if ($(password)) {
                $("#email_login_details").removeClass("disabled");
            } else {
                $("#email_login_details").addClass("disabled");
            }
        });

2 个答案:

答案 0 :(得分:1)

使用JQuery的focus事件处理程序。

$("input").focus(function () {

console.log('enabling checkbox');

$('#email_login_details').removeAttr('disabled');

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<body>

<form action="#">
User name:<br>
<input type="text" name="name">
<br>
User password:<br>
<input type="password" id="password" name="password">

<input type="checkbox" name="email_login_details" id="email_login_details" value="Car" disabled>Email login details

<!-- Note: I want firstly disabled this checkbox. When I type password then enable this checkbox. -->

</form>
</body>
</html>

答案 1 :(得分:1)

以下是您对边缘盒进行一些增强后所要求的工作示例

$("#password").change(function() {
  let password = $("#password").val()
  console.log(password);
  if (password) {
    console.log()
    $("#email_login_details").removeAttr("disabled");
  } else {
    $("#email_login_details").prop("checked", false);
    $("#email_login_details").attr("disabled", "true");
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="#">
  User name:<br>
  <input type="text" name="name">
  <br> User password:<br>
  <input type="password" id="password" name="password">

  <input type="checkbox" name="email_login_details" id="email_login_details" value="Car" disabled>Email login details

  <!-- Note: I want firstly disabled this checkbox. When I type password then enable this checkbox. -->

</form>