Given the following HTML structure:
<input class="addon-thumb" type="checkbox" name="foo"/><label for="foo"><img class="addon-thumb" src="" title="bar" alt="foo"/></label>
And using JQuery, how do I toggle the class of the img inside the label tag to be "selected" when the checkbox is selected?
It doesn't matter if it retains the other class (addon-thumb) or not, as long as if the box is deselected it would get that class back.
EDIT:
I have tried both of the below suggestions inside $(document).ready(function(){});
and for whatever reason this is not working for me. I was actually doing something very close to the below in the first place. Any more help would be appreciated.
You can simply do this:
$(":checkbox").change(function () {
$(this).next("label").children("img").toggleClass("selected", this.checked);
});
If the position of the label can change, then you can find the correct associated label based on name
:
$("[for=" + this.name + "]").children("img")
.toggleClass("selected", this.checked);