I’d like to add a jQuery handler for each of my checkbox inputs so that when their value is changed (via a click directly on them or via a click on the labels bound to them via the “for” attribute), to true (or checked=”checked”) a class called “selected” is added to the parent li element.
Conversely, when the checkbox is unchecked by a click event, I want to remove the “selected” class from the li element.
<li class="section">
<label class="left" for="my_ad_stacked">Left Label</label>
<input type="checkbox" name="my_ad_stacked" id="my_ad_stacked" value="true" />
<label for="my_ad_stacked" class="description check ">label info goes here</label>
</li>
I know that If I know the id or class of an element, I can use $(‘myElement’).addClass(‘selected’) and $(‘myElement’).removeClass(‘selected’). I’m just not certain how to attach the behavior, dynamically to all checkbox elements, and their “for” bound labels.
This binds a
changeevent to everyinputelement of typecheckbox. When one changes, the event handler function runs, and toggles theselectedclass on the closestlielement.In the event handler,
thisrefers to the checkbox that has changed, so this will work for all checkboxes (assuming all checkboxes on your page have anlielement ancestor).Here’s an example fiddle showing this in action.