This post is about removing a table row on user click. I needed this functionality for a project of mine. Online application had a table with data that user can dynamically add and remove. With progressive enhancement I also need to add a functionality to one of the tables that enables users to delete table rows when that table row is clicked.
jQuery code to delete clicked table row came out to be surprisingly short, only 3 lines of code.
// Select all table cells to bind a click event $('table td').click(function(){ $(this).parent().remove(); });
Here, we are first selecting all table cells to bind our click event. On user click to any table cell click
event fires. In the click event we are removing <td>
’s parent, which is <tr>
, thus removing whole row.
By popular user demand I’m including an example that lets deleting a table row on delete image click. Here is our HTML table:
<table> <tr> <td>row 1, cell 1</td> <td><img class="delete" src="del.gif" /></td> </tr> <tr> <td>row 2, cell 1</td> <td><img class="delete" src="del.gif" /></td> </tr> </table>
Here is jQuery code to delete a row on delete image click:
$('table td img.delete').click(function(){ $(this).parent().parent().remove(); });
See demos here.
Bonus: Also delete a table row from database
The code above is enough if you don’t need to also delete a record from your database table. In my case I had to set up a server side code to do that. With one extra AJAX call to my server side script the functionality was ready.
$('table td').click(function(){ $.get('deleteRow.php', {id: $(this).parent().attr('id')}, function(){ $(this).parent().remove(); }); });
In the jQuery code above, instead of removing table row straight away we are making an AJAX call to our server side code that also removes that row from our database and then on AJAX call completion we removing table row.