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.
Try this...
$(":checkbox").on('click', function(){
$(this).parent().toggleClass("checked");
});
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);
});
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.
来源:https://stackoverflow.com/questions/14468156/if-checkbox-checked-add-class-to-parent-element