0

I'm trying to target various blocks that have the class "checkbox" and they all contain a label and an input of checkbox type. When clicking anywhere inside .checkbox area (except over the input) the "checked" value is being toggled, when clicking over the input, the value just stays the same. Could someone explain to me why is it acting like that (why when clicking the input, the value doesn't toggle)?

HTML

<div class="checkbox">
    <label for="a">a</label>
    <input type="checkbox" name="a" checked>
</div>
<div class="checkbox">
    <label for="b">b</label>
    <input type="checkbox" name="b">
</div>

JQuery

function toggleProp(el) {
    $(el).prop("checked", !el.prop("checked"));
}

$(".checkbox").click(function () {
    toggleProp($(this).find("input"));
});

Live example

edit:

  • What it should have done:

    Clicking anywhere inside of the .checkbox areas, the value of input's checked property should have been toggled from true to false or vice versa.

  • What it does:

    Clicking anywhere inside of .checkarea areas except (!) the input toggles the value. When clicking the input, the value stays the same which is not wanted

Adonis K. Kakoulidis
  • 4,951
  • 6
  • 34
  • 43

1 Answers1

0

Found it.

I had to also add this part:

$(".checkbox input").click(function(e) {
    e.stopPropagation();
});

This way, when clicking the input, it won't trigger its parent's click event

Adonis K. Kakoulidis
  • 4,951
  • 6
  • 34
  • 43