Jquery if checkbox is checked add a class

前端 未结 7 2172
梦如初夏
梦如初夏 2020-12-06 01:17

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

My jquery:

$(\'input\').attr(\"checked\").change(function(){
$(\'div.menuitem\').addClass(\"me         


        
7条回答
  •  情话喂你
    2020-12-06 01:44

    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..

提交回复
热议问题