Silverburch
Silverburch

Reputation: 477

jQuery selectable() not responding to checkbox ticks

I've got a set of checkboxes which can all be checked/unchecked easily by dragging the mouse over the labels using selectable() plugin. But if I specifically click a checkbox input box instead of its label, nothing happens. I've tried all kinds of combinations using the filter, but nothing seems to work other than using 'label'. I want the behaviour to be the same whether the user drags over the input boxes or the labels. Several hours on this now, please help! Fiddle below.

<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/

Upvotes: 0

Views: 106

Answers (2)

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

For Me I wouldn't use the selectable() I'll just use click() event .. Here is how

$('.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>

For reference you can take a look at jQuery difference between change and click event of checkbox

Upvotes: 1

WeiYuan
WeiYuan

Reputation: 5992

The checkbox is another DOM over the div, so you must attach the same event to it like below:

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

DemoL http://jsfiddle.net/86njvLrw/

Upvotes: 1

Related Questions