views:

88

answers:

1
+1  Q: 

next() not working

Hi All,

I have a table structure:

<tr>
  <td>
    <a href="#" class="xx"></a>
  </td>
  <td>
    data
  </td>
</tr>
<tr>
  <td> 
    <img src="#" class="cc" />
  </td>
</tr>
<tr>
  <td>
    <a href="#" class="xx"></a>
  </td>
  <td>
    data2
  </td>
</tr>
<tr>
  <td> 
    <img src="#" class="cc" />
  </td>
</tr>

Now, on load, 2nd and 4th row are hidden. On click of <a> its immediate next rows <img> should come into display.

For that i have written:

$("a.xx").click(function (event) {
  $(this).next(".cc").toggleClass();// not working
});

Any clue?

EDIT:

On click of 1st row's <a>, it should show 2nd row's <img> and on click of 3rd <a>, it should show 4th row's <img>, and only one <img> at a time.

CSS

.cc {
  display: none;
}
+3  A: 

EDIT: Based on further clarification, you want a second click to close an open image.

Do this:

$(this).closest('tr').next('tr').find("img.cc").toggle()
       .closest('tr').siblings('tr').find("img.cc").hide();

or this, which is a little more efficient:

$(this).closest('tr').next('tr').find("img.cc").toggle(0, function() {
       var $th = $(this);
       if( $th.is(':visible') )
           $th.closest('tr').siblings('tr').find("img.cc").hide();
});

EDIT: Based on clarification, seems like you want to show the image in the next row, and hide the rest.

Do this:

$(this).closest('tr').next('tr').find("img.cc").show()
       .closest('tr').siblings('tr').find("img.cc").hide();

Original answer:

Do this:

$(this).closest('tr').next('tr').find("img.cc").toggleClass('someClass');

jQuery's .next() only looks at the siblings of the element.

You need to traverse up to the .closest() <tr> element, get the .next() row, then .find() the .cc element.

I also assume you're passing a class name to .toggleClass() instead of calling it without an argument.

Otherwise, to display the <img> you would probably use .show().

patrick dw
+1 didn't know about `closest()`
robertbasic
I tried $(this).closest('tr').next('tr').find("img.cc").toggleClass("cc"); but its only opening, not closing the <td>if I click on first row then 2nd rows img should be in display mode, if I click on 3 rd row then any open image should close and 4 th row image should open
Wondering
I have edited my post
Wondering
@Wondering - I see. I'll update in a minute.
patrick dw
Thanks for ur help, but i think my qs is not clear, see now its working, but if I 2 nd time click on the <a> ideally it should close the <img>
Wondering
@Wondering - I'll update again.
patrick dw
its working.thanks.
Wondering