if checkbox checked add class to parent element

守給你的承諾、 提交于 2019-12-01 05:56:53

Try this...

$(":checkbox").on('click', function(){
     $(this).parent().toggleClass("checked");
});

Example

Greetings.

You can use .change() to bind to the change event; then, use .closest() and .toggleClass() to add or remove the selected classname from the grandparent element.

$("input:checkbox").change(function(){
  $(this).closest(".table-col").toggleClass('selected', this.checked);
});

See it here.

Give your checkbox a name so jQuery can hook to it:

$('input[name=foo]').is(':checked')

$(this) will only refer to your checkbox (so that you can go up to it's grandparent as per your code) when you're in an event handler invoked by having assigned it to the checkbox element as @cimmanon hinted at.

So if you assigned the .change() handler to your checkbox, $(this) will refer to your checkbox. You can actually do this in one line because you probably want to toggle the "selected" class on or off:

    $(":checkbox").change(function () {
    $(this).parent().parent().toggleClass('selected');
         });

Otherwise $(this) refers to the control that raised the event for example if you are executing this code in response to a button click handler, $(this) will refer to the button.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!