jQuery: Delete a row from a table on user click
In an exciting in-the-works project (will talk about it later), I was required to create a dashboard from where users would be able to edit certain tabular data. Each row of data had a delete option on the extreme right. If the user wishes to delete an entry from the table, they can simply click on the respective delete button and the entire row would be dropped from the table. This can be achieved with a simple two line jQuery.
This is a snapshot of the table with 5 demo entries.
If the user clicks on the delete (cross) link on the third row, the entire row is deleted and the table would then look like the following:
The user can delete as many rows as they want (as long as there are rows left to delete, obviously
).
In jQuery there is a pre-built function called remove() that would do the trick for us, so the real work comes down to simply selecting the object that triggers the delete (in our case, the cross image) and the row that needs to be deleted.
Here’s the code that you need:
$(‘table tr td img.deleteimage’).click(function(){
$(this).parent().parent().remove();
});
});
Typically in an HTML table, the hierarchy is table > tr (row) > td (table cell). The cross (delete) image has a class assigned called “deleteimage”. If you follow the jQuery script, when the image is clicked, its parent’s parent object is removed. The image’s parent object is the cell (td) and the cell’s parent is the row (td). Thus, the when the img is clicked, the corresponding row (td) along with all the cells and content is removed.
Latest posts by Smarajit Dasgupta
- Playing with HTML5 - July 29th, 2011
- CSS Tutorial - June 7th, 2011
- 5 Tips for optimizing and cleaning up CSS - April 8th, 2011
- Introduction to HTML5 input types - April 1st, 2011
- Text level Semantics in HTML5 - March 17th, 2011


