【问题标题】:How could I set up an event handler for my checkbox for checked and unchecked?如何为选中和未选中的复选框设置事件处理程序?
【发布时间】:2021-12-19 19:56:43
【问题描述】:

我正在使用 Bootstrap 5 和 jQuery 3.6.0,我一直在努力寻找解决方案,但我发现的所有东西都没有奏效,因为它已经过时了。

我实际上想要做的只是为选中或未选中的复选框设置一个事件处理程序。该复选框是一个 Bootstrap 开关样式的复选框。

我已经设法得到它,以便激活未选中部分的代码,但是我认为它没有被正确激活。但我无法得到它,以便事件在被检查时激活。

我的 HTML:

<div class="form-check form-switch" id="checkboxLondon">
              <input class="form-check-input" type="checkbox" id="flexSwitchCheckDefault">
              <label class="form-check-label" for="flexSwitchCheckDefault">London</label>
</div>

我的 jQuery/JS:

$('#checkboxLondon').click(function () {
    console.log("This works")
    if ($(this).is(":checked")){
      console.log("Checkbox is checked");
    } else if ($(this).is(":checked") == false) {    
      console.log("Checkbox is unchecked");
    }
});

【问题讨论】:

标签: javascript jquery twitter-bootstrap checkbox


【解决方案1】:

在您的复选框上使用.change() 状态处理程序,而不是在父 div 上,然后使用.is() 检查复选框何时被选中

$('#flexSwitchCheckDefault').change(function(){
  console.log($(this).is(':checked'))
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-check form-switch" id="checkboxLondon">
              <input class="form-check-input" type="checkbox" id="flexSwitchCheckDefault">
              <label class="form-check-label" for="flexSwitchCheckDefault">London</label>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-21
    • 2015-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-05
    • 1970-01-01
    • 2018-12-28
    相关资源
    最近更新 更多