Ben Gordon
Ben Gordon

Reputation: 437

Why won't the closest() selector work in this instance?

I am trying to activate toggleClass() on a specific image when clicking on a radio button. I have been trying for ages to get it to work but can't. I can manage to select a parent element of the radio button but nothing proceeding it. I have tried next(), nextAll() and closest(). All of which don't seem to do what I'm trying to achieve.

Here is my jQuery function:

$(document).ready(function() {
  $("input[type=radio]").change(function () {
    if (this.value == "AM") {
      $(this).closest('img[title="am"]').toggleClass('houdini');
    } else if (this.value == "PM") {
    alert('PM');
/*      Something here */
    } else {
        return false();
    }
  });
});

and my HTML:

<tr>
    <td><input type="radio" name="bisley" value="AM" />AM<input type="radio" name="bisley" value="PM" />PM<span class="compname">Bisley</span></td>
    <td>Fit more into less space</td>
    <td class="time"><img src="/images/generic/openday/tick.png" alt="tick" title="am" class="houdini" />10.00AM</td>
    <td class="time"><img src="/images/generic/openday/tick.png" alt="tick" title="pm" class="houdini" />1.30PM</td>
</tr>

Upvotes: 2

Views: 329

Answers (2)

xkeshav
xkeshav

Reputation: 54016

change to

$(this).parent().children('img[title="am"]').toggleClass('houdini');

SEE DEMO

Upvotes: 0

lonesomeday
lonesomeday

Reputation: 237845

closest searches ancestor elements; next and nextAll search sibling elements. The img element you want is the child of a sibling element, so you'll need a more complex statement. Have a go with this:

$(this).closest('tr').find('img[title="am"]').toggleClass('houdini');

This says "find the closest ancestor tr element, then find img[title="am"] within that.

Upvotes: 3

Related Questions