if checkbox checked add class to parent element

纵饮孤独 提交于 2019-12-19 08:12:44

问题


I have a table with checkboxes looking like this:

<td class="table-col" >
  <div class="group-one" >
    <input type="checkbox"  />
  </div>
</td>

What I want to do is when the checkbox is checked to apply a "selected" class to "table-col".

if ($('.table-col').find(':checked')) {
    $(this).parent().parent().addClass('selected');
}

I looked at many post with a similar solution like above but it doesn't seem work for me. I'm not sure why but this is pointing to HTMLDocument not the element.

(edit) On this page there will be marked checkboxes, those which I want to apply "selected". On comments @cimmanon mentioned event handling. I'll need to look this up. Thanks for the answers too!

(edit)

<td class="table-col">
<div class="group-one">
    <input type="checkbox" checked="checked"/>
</div>
</td>

So after the pageloads there will be boxes marked (i think they will always contain checked="checked" -- not sure) checkboxes. These are the ones that need a new style. There is no need for the interaction of clicking them and applying a style but very cool nonetheless.


回答1:


Try this...

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

Example

Greetings.




回答2:


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.




回答3:


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

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



回答4:


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



来源:https://stackoverflow.com/questions/14468156/if-checkbox-checked-add-class-to-parent-element

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