jQuery selectable()不响应复选框

时间:2018-12-30 20:40:41

标签: jquery jquery-ui-selectable

我有一组复选框,可以通过使用selectable()插件将鼠标拖到标签上来轻松地选中/取消选中所有复选框。但是,如果我专门单击复选框输入框而不是其标签,则什么也不会发生。我已经尝试过使用过滤器进行各种组合,但是除了使用“标签”之外,似乎没有其他工作。无论用户将鼠标拖动到输入框还是标签上,我都希望行为相同。现在需要几个小时,请帮忙!小提琴在下面。

<form>
 <div class='myBoxes'>

  <label>Check 1<input type="checkbox" id="chk1" /> </label>
  <label>Check 2<input type="checkbox" id="chk2" /> </label>
  <label>Check 3<input type="checkbox" id="chk3" /> </label>
  <label>Check 4<input type="checkbox" id="chk4" /> </label>

 </div>
</form>



$(".myBoxes").selectable({

  filter: 'label',

  stop: function() {
    $(".ui-selected input", this).each(function() {
      this.checked = !this.checked;

      if ($(this).is(':checked')) {
        console.log($(this));
        $(this).parent().addClass("LabelHighlight")
      } else {
        $(this).parent().removeClass("LabelHighlight")
      }

    });
  }
});



 label {
  display: block;
  padding: 7px;
  width: 120px;
  margin-bottom: 14px;
  border: 1px solid red;
}

label.ui-selecting {
  background: lightgreen;
}

.LabelHighlight {
  background: lightgreen;
}

http://jsfiddle.net/y7xk032m/

2 个答案:

答案 0 :(得分:1)

此复选框是div上的另一个DOM,因此您必须将相同的事件附加到它,如下所示:

$("input[type='checkbox']").click(function(event){
    if ($(this).is(':checked')) {
    console.log($(this));
    $(this).parent().addClass("LabelHighlight")
  } else {
    $(this).parent().removeClass("LabelHighlight")
  }
});

演示http://jsfiddle.net/86njvLrw/

答案 1 :(得分:1)

对我来说我不会使用selectable()我只会使用click()事件..这是

$('.myBoxes label').on('click' , function(e){
    $("input:checkbox" , this).change();
});
$("input:checkbox").on("click" , function(e){
    $(this).closest('label').toggleClass("LabelHighlight");
});
label {
  display: block;
  padding: 7px;
  width: 120px;
  margin-bottom: 14px;
  border: 1px solid red;
}

label.ui-selecting {
  background: lightgreen;
}

.LabelHighlight {
  background: lightgreen;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form>
  <div class='myBoxes'>

    <label>Check 1<input type="checkbox" id="chk1" /> </label>
    <label>Check 2<input type="checkbox" id="chk2" /> </label>
    <label>Check 3<input type="checkbox" id="chk3" /> </label>
    <label>Check 4<input type="checkbox" id="chk4" /> </label>

  </div>
</form>

作为参考,您可以看看jQuery difference between change and click event of checkbox