1

Hello and I know there are few almost same problems around, but I couldn't find solution with answers given on them, so im first time posting here.

I have simple li and label inside of it

<li class="task">
    <input type="checkbox" id="task-1" />
    <label for="task-1">Random text></label>
</li>

and my jQuery for triggering "done" class is:

$(".task").click(function (e) {
    var cb = $(this).find(":checkbox")[0];
    if (e.target != cb) cb.checked = !cb.checked;
    $(this).toggleClass("done", cb.checked);
});

this actually works fine when clicked on checkbox or on li background, but doesn't work when clicked on label.

My another jQuery that works when clicked on checkbox and label, but not on background is:

$(".task input").change(function () {
    $(this).closest('.task').toggleClass('done', $(this).is(':checked'));
});

How can I create jQuery that will activate event when clicked on checkbox, label, or background of li? Thank you and sorry for any mistakes during post.

Fiddle: https://jsfiddle.net/0j7e69o1/2/

B.Doe
  • 37
  • 1
  • 6

1 Answers1

0

This is because the label has default click functionality which means it gives focus to the element with the ID that is referenced in it's for attribute. It's doing that when you click.

You can remove the for attribute to fix this, as in this example:

https://jsfiddle.net/0j7e69o1/3/

Preferred: Another solution is to prevent the default click with javascript:

$('.tasks label').click(function(e) { e.preventDefault(); } );

Here we bind a click event to every label within the tasks element and use preventDefault() (more here) to stop the default event from occuring. This is preferred as it leaves your mark-up with it's helpful for attributes intact!

https://jsfiddle.net/0j7e69o1/5/

Community
  • 1
  • 1
Toni Leigh
  • 4,830
  • 3
  • 22
  • 36