1

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

bah! thats too easy. Thanks! actually the image beside the checkbox is an ajax loading image..so the toggling is a little more complicated (I probably need to hide it in the ajax success callback).
@bba - You can call .change() no params, on the checkbox to affect the image the way it would be as if someone changed the check via the UI...this can be useful for greatly reducing your code, just triggering the code in the handler you already have. I'm not sure it helps since I don't know your exact setup, just throwing that out there in case it does :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.