Reputation: 15231
I have the following:
<form id="my_form">
<input type="checkbox" name="a" value="a"> Check <img src="..." />
</form>
To handle the check and uncheck events I do (and this works):
$('#my_form :checkbox).click(function() {
if($(this).is(':checked')) {
//...
}
//...
});
My question is: inside of that click function, how can I select the <img>
tag that is right beside the checkbox? Can I do this without specifying an ID for the image? ..by "select" I mean that I need to be able to hide() and show() it. Thanks
Upvotes: 1
Views: 29
Reputation: 630607
You can use .next()
since it's the next (immediate next, this is important) sibling element, like this:
$('#my_form :checkbox').click(function() {
if(this.checked) {
var img = $(this).next('img');
}
});
I think what you're ultimately after is easiest done with .toggle(bool)
, like this:
$('#my_form :checkbox').change(function() {
$(this).next('img').toggle(this.checked);
});
This will show the <img>
when checked, and hide it when it's not. Note that I used .change()
here, since that's the event you usually want when dealing with a checkbox to always get the correct state.
Upvotes: 1