Jquery how to add attribute to father object?

Problem

So here's the situation

I have this jquery code

$("li").click(function(){
var checkbox = $(this).find("input[type='checkbox']");

    if( checkbox.prop("checked") == "" ){
        checkbox.prop("checked", true);
        (this).addClass("on");
    } else {
        checkbox.prop("checked", false);
        ("li").removeClass("on");
    }
});

And this html

<ul id="id_priori">
<li><label for="id_priori_0"><input id="id_priori_0" name="priori" type="checkbox"> Hola</label></li>
</ul>

What i want to do is add / remove the class on the

  • depending on if the checkbox is checked or unchecked , but it doesnt work

    Problem courtesy of: Maks
  • Solution

    You could simplify this to just

    $("li").click(function(){
        var self = $(this),
            checkbox = self.find("input[type='checkbox']")[0];
    
        // change the checkbox state
        checkbox.checked = !checkbox.checked;
    
        self.toggleClass( 'on', checkbox.checked );
    });
    

    End even better to delegate the handler to just the ul

    $("#id_priori").on('click', 'li', function(){
        var self = $(this),
            checkbox = self.find("input[type='checkbox']")[0];
    
        // change the checkbox state
        checkbox.checked = !checkbox.checked;
    
        self.toggleClass( 'on', checkbox.checked );
    });
    

    Demo at http://jsfiddle.net/gaby/W9D8n/2/


    Update

    To make the prechecked li element to have the on class add

    .find(":checkbox").each(function(){
       $(this).closest('li').toggleClass('on', this.checked);
    });
    

    to the code.

    $("#id_priori").on('click', 'li', function(){
        var self = $(this),
            checkbox = self.find(":checkbox")[0];
    
        // change the checkbox state
        checkbox.checked = !checkbox.checked;
    
        self.toggleClass( 'on', checkbox.checked );
    
    }).find(":checkbox").each(function(){
    
        $(this).closest('li').toggleClass('on', this.checked);
    
    });
    

    Demo at http://jsfiddle.net/gaby/W9D8n/3/

    Solution courtesy of: Gaby aka G. Petrioli

    Discussion

    Couple mistakes:

    Change:

    ("li").removeClass("on");
    

    To:

    $("li").removeClass("on"); // You are missing the $
    

    Change:

    (this).addClass("on");
    

    To:

    $(this).addClass("on"); // You are missing the $
    

    Also, use .is(:checked') to see if the checkbox is checked.

    Try this:

    $(document).ready(function () {
        $('li').addClass('on');
        $("li").click(function () {
            var checkbox = $(this).find("input[type='checkbox']");
            if (checkbox.is(':checked')) {
                $(this).addClass("on");
            } else {
                $(this).removeClass("on");
            }
        });
    });
    

    JSFiddle Demo

    Discussion courtesy of: imbondbaby

    This recipe can be found in it's original form on Stack Over Flow.