Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery if checkbox is checked add a class

Tags:

jquery

I am trying to add a class when a checkbox is checked.

My jquery:

$('input').attr("checked").change(function(){
$('div.menuitem').addClass("menuitemshow");
})
like image 469
Rails beginner Avatar asked Aug 01 '11 14:08

Rails beginner


1 Answers

You should not use $("input") to select a checkbox, input will select all inputs. Instead you can use input:checkbox:

$('input:checkbox').change(function(){
    if($(this).is(":checked")) {
        $('div.menuitem').addClass("menuitemshow");
    } else {
        $('div.menuitem').removeClass("menuitemshow");
    }
});

Basically what this does is execute whatever is inside the function(){} when the checkbox is changed. Then you can just use jQuery is to check if the checkbox is checked or not..

like image 148
betamax Avatar answered Oct 23 '22 09:10

betamax