Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clicking on label doesn't trigger click event

I have this code:

<label><input type="checkbox">True?</label>

and

$("label").click(function () {
  $(this).toggleClass("active");
});

When I click the checkbox class toggles, when I click "True?" nothing happens. Why?

Then if I don't wrap checkbox in label everything works fine.

<input type="checkbox" id="c1"><label for="c1">True?</label>

This is so weird... And it doesn't matter if I put "for" or not.

http://jsfiddle.net/zufs6ueh/1/

What is going wrong here?

like image 592
Andrey Avatar asked Jan 19 '15 17:01

Andrey


2 Answers

This would be safer to use:

$(function() {

    $('input[type="checkbox"]').bind('change', function (v) {

        if($(this).is(':checked')) {
            $(this).parent().addClass('active');
        } else {
            $(this).parent().removeClass('active');
        }
    });

});

Using change instead of click allows for people that navigate forms using the keyboard.

like image 94
rwacarter Avatar answered Sep 23 '22 02:09

rwacarter


Clicking the label also triggers a click on the input so bind the change event to the checkbox itself:

$(function(){
    $("label input").on("click",function(){
	$(this).parent().toggleClass("active");
    });
});
.active {color:red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label><input type="checkbox" />True?</label>

Or With CSS 3

If you don't need to support old browsers, you could use the :checked pseudo-class in CSS instead:

input[type=checkbox]:checked + label {color:red;}
<input type="checkbox" id="demo" name="demo"> 
<label for="demo">True?</label> 
like image 38
Moob Avatar answered Sep 23 '22 02:09

Moob