tags:

views:

62

answers:

2

I have a table in html as follows

<table>
<tbody>
<tr>
<td>test content</td>
<td><input type="button" onClick="remove()"></td>
</tr>
....
...

</tbody>
</table>

now if the same pattern continues, i want to remove a row if a remove button is clicked on that row. how do i achieve the same with jQuery?

+2  A: 

Try this:

<input type="button" onClick="$(this).parent().parent().remove();">

Or you can make it more generic like this:

<script>
  $(document).ready(function()
  {
    $(".btn").click(function(){
      $(this).parent().parent().remove();
    });
  });
</script>

<tr>
  <td><input type="button" class="btn"></td>
</tr>
Sarfraz
probably want to use a class instead of an id though.
Sam Hasler
@Sam Hasler: agreed and fixed, thanks for informing that :)
Sarfraz
if he wants to remove the row, I would include a 'tr' inside your code, in case he ever adds any more elements like a div. Then your code will break, but @alt's code won't.
Martin
@Martin: very good point, thanks
Sarfraz
+8  A: 

Nicer:

$(this).closest('tr').remove();

More on closest()

<input type="button" onClick="$(this).closest('tr').remove();">

This has the benefit of working no matter what your HTML looks like in the cell.

altCognito
Cool... :) Thanks
Amit