tags:

views:

430

answers:

1

I have a table that looks like this:

<table>
    <thead>
     <!-- random table headings -->
    </thead>
    <tbody>
     <tr class="readonly">
      <td><input type="text" readonly="readonly" name="bookings[start][]" class="date" value="start"/></td>
      <td><input type="text" readonly="readonly" name="bookings[end][]" class="date" value="end"/></td>
      <td><input type="text" readonly="readonly" name="bookings[comment][]" value="comment"/></td>
      <td>
       <button type="button" class="control edit" title="Edit this row">Edit</button>
       <button type="button" class="control delete" title="Delete this row">&times;</button>
       <!-- delete button needs to know the posistion of the row
            in the table so that it can remove its array entry -->
      </td>
     </tr>
     <!-- ^ inserted as required by the button in tfoot -->
    </tbody>
    <tfoot>
     <tr>
      <td><input type="text" id="startinput" class="date" value=""/></td>
      <td><input type="text" id="endinput" class="date" value=""/></td>
      <td><input type="text" id="commentinput" value=""/></td>
      <td><button type="button" class="control add" title="Add to the table">+</button></td>
     </tr>
    </tfoot>
</table>

In order to correctly implement the delete button, the index of the row in which the button can be found needs to be calculated. How can I do this in jQuery? Here's the current code:

$("button.delete").live("click",function()
{
    var row = $(this).parent().parent();
    row.addClass("deleting");
    if(confirm("delete this row?"))
    {
     var row idx = /*???*/;
     datelist.bookings.splice(idx,1);
     row.remove();
    }
    else
    {
     row.removeClass("deleting");
    }
});

Thanks.

+3  A: 

This will give you a zero-based index of the row within the tbody.

var row_idx = row.prevAll().length;

Just FYI, technically the tfoot should appear before the tbody (for correct HTML). Also, it's technically possibly to have multiple tbody elements.

cletus