Using jQuery to Delete a Row in a Table by just Clicking on it

Here’s a very simple way of deleting a row in a table, when a user clicks on it. With jQuery, the efforts required to achieve this requirement is just 2 lines of code.

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title></title>
<
script src="Scripts/jquery-1.3.2.js"
type="text/javascript"></script>
<
script type="text/javascript">
$(document).ready(function() {
$('table tr.del').click(function() {
$(this).remove();
});
});
</script>
</
head>
<
body>
<
table border="1">
<
tr class="del">
<
td>Row 0 Column 0</td>
<
td >Row 0 Column 1</td>
</
tr>
<
tr class="del">
<
td>Row 1 Column 0</td>
<
td>Row 1 Column 1</td>
</
tr>
<
tr class="del">
<
td>Row 2 Column 0</td>
<
td>Row 2 Column 1</td>
</
tr>
<
tr class="del">
<
td>Row 3 Column 0</td>
<
td>Row 3 Column 1</td>
</
tr>
<
tr class="del">
<
td>Row 4 Column 0</td>
<
td>Row 4 Column 1</td>
</
tr>
<
tr class="del">
<
td>Row 5 Column 0</td>
<
td>Row 5 Column 1</td>
</
tr>
</
table>
</
body>
</
html>

When you preview the code, you see a screen similar to the following :

image

Now click on a Row , let us say Row 3. What do you observe? Well it gets deleted!

image

If you want to achieve the same in an ASP.NET GridView, check out my article over here

Some ASP.NET GridView UI Tips and Tricks using jQuery



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

5 comments:

Toi said...

if you can show me how to hide (not delete) it, that means hide it and leave a small mark to show that row again when the mark is clicked, then I'll be very thankful.

Sean said...

You would just have to change the .remove() to .hide()

cigraphics said...
This comment has been removed by the author.
cigraphics said...

you can use another method just add an id to the whole table and you won't need to add class to every tr

$(document).ready(function() { $('table#test tbody tr').click(function() {
$(this).css('backgroundColor', '#CCC').fadeOut('slow', function() { $(this).remove() });
});
});

haiku said...

good one cipgraphics. I feel author wanted to identify rows which can be deleted, hence added the class. Both approach are good in their own applications.