tags:

views:

96

answers:

2

I have a couple of tables with similar structures like this:

<table>
<tbody>
  <tr>content</tr>
  <tr>content</tr>
  <tr>content</tr>
  <tr>content</tr>
  <tr>content</tr>
  <tr>content</tr>
  <tr>content</tr>
  <tr>content</tr> ..etc
    --- The fake button is added here
    <div class="addrow">Add another</div>
</tbody>
</table>

UPDATE: All the rows have the same draggable class.

Since this is a long list, I have a need to toggle the rows one at a time. I just need to show the first row, of course, the rest should be toggled.

The action is when I click a dynamic fake button, it will show row no. 2, and clicking again will show another next row.

This is what I have done so far:

$("table#field_fruit_values tr.draggable").not(':first').hide();
$("table#field_vegetables_values tr.draggable").not(':first').hide();


$("body.form table.content-multiple-table tbody").append('<div class="addrow">Add</div>');

$(".addrow").click(function() {
  var  hiddenRow = $(this).prev('tr.draggable');
  $(this).prev(hiddenRow + 1).show();
    //if (hiddenRow + ':last').length) { // <= silly logic
     // $(this).hide();
    //}
});

The button only works for one row. I must have done something wrong :)

When the final is reached, I also want the button to disappear.

Sorry if this question sound silly.

Any help would be very much appreciated.

Thanks.

A: 
prev(hiddenRow + 1)

hiddenRow is a jquery object.

You can't add one to that, as far as I know.

What you probably want to do is create a class called 'visible'. Each time you make a row visible, give it that class. Then, to find the last visible row:

$(this).closest('table').find('tr.visible').filter(':last')

DA
+1  A: 

You can do it a bit more concise with less DOM traversal like this:

$(".addrow").click(function() {
   var row = $(this).prev("table").find("tr:hidden:first");
   if(row.length) row.show();
   else $(this).hide();
});​

Also change your .append() to .after() to get valid html (a <div> in a <tbody> is invalid):

$("table.content-multiple-table").after('<div class="addrow">Add</div>');
Nick Craver
You answered my question again very well. Thank you very much, Nick.
swan
doesn't prev() and next() only get siblings? In the example the <div> was a sibling of <tr>
hunter
@Hunter - that's the second part of the answer, it's not valid html...need to put the div after the table, not in the tbody :)
Nick Craver