首页 > 解决方案 > 如果选中任何其他复选框,请取消选择特定复选框

问题描述

我有一个客户的最后一分钟请求将表单元素更改为多项选择......所以我将它们更改为复选框,一切都很好。现在复选框是动态生成的,它们之间的唯一一致性是包含“以上都不是”的复选框,现在我有以下内容:

$('input[type=checkbox]').change(function () {
            if (this.parentNode.innerHTML.indexOf("None of the above") >= 0) {
                console.log("Is none of the above")
                if (this.checked) {
                    console.log("is checked")
                    $(this).closest('.js-form')
                        .find('input[type=checkbox]').not(this)
                        .prop('checked', false);
                }
            }

这在一定程度上有效,如果有人选择复选框然后选择“以上都不是”,它会清除其他选择。

我的问题只是我想要一个 else:即,如果您没有选择以上任何一项,我想要您所做的任何选择都将上述复选框中的任何一项标记为选中,false。

如果复选框不等于“以上都不是”复选框,则将“以上都不是”复选框标记为选中,false。

到目前为止,我似乎通过上述代码的变体来促进的是取消选中所有复选框

标签: jquery

解决方案


你几乎在那里,但是你将香草与 jQuery 混合在一起,虽然这很好,但它可能会让人感到困惑 - jquery 允许你$(this)在他们的事件侦听器中使用,所以你尝试了,this但它在这里不一样。因此,如果不仅仅是为了一致性和可读性,最好尝试并坚持使用其中一种

如果任何其他复选框被选中,我还添加了取消选择“以上都不是”的位。

$('input[type=checkbox]').change(function() {
  if ($(this).parent().text().trim().toLowerCase() === "none of the above") {
    console.log("Is none of the above")
    if ($(this).prop('checked')) {
      console.log("is checked")
      $(this).closest('.js-form')
        .find('input[type=checkbox]').not(this)
        .prop('checked', false);
    }
  } else {
    $(this).closest('.js-form')
      .find('input[type=checkbox]').each(function() {
        if ($(this).parent().text().trim().toLowerCase() === "none of the above") $(this).prop('checked', false)
      })
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='container'>
  <div class='js-form'>
    <label><input type='checkbox' /> Checkbox 1</label>
    <label><input type='checkbox' /> Checkbox 2</label>
    <label><input type='checkbox' /> Checkbox 3</label>
    <label><input type='checkbox' /> Checkbox 4</label>
    <hr>
    <label><input type='checkbox' />None of the above</label>

  </div>


推荐阅读