Using JQuery to remove a table row.

This is a tutorial on how to remove a HTML table row using JQuery. This can be useful if you intend on deleting table rows using Ajax¬†and you don’t want to refresh the page.

Let’s start off with the simplest approach. Below is an example of a HTML table that represents a shopping cart:

A few things to note about the table above:

  1. The TR elements in our HTML table have all been given their own unique ID. For example, the first row has the ID “item_1“, whereas the last row has been given the ID “item_3“. This is important, as it allows us to identify the exact row that the user wants to delete.
  2. The 4th TD in each row contains a Button element. In the example above, I have added an inline onclick event to each Button element.
  3. When a button is clicked, a function called “remove” is called and the ID of the parent TR element is passed in as a string.

Now, let’s create our remove function:

As you can see, the function above is pretty straight-forward. It takes in the ID of a TR element and it deletes the element by calling JQuery’s remove method.

Fading out a table row.

In many cases, you might want to fade the table row out. This approach allows our users to observe the row as it is being removed. The problem with the remove approach above is that it can happen way too fast.

To fade the table row out, we will make a small modification to our remove function:

In the example above, we faded the TR element out by using JQuery’s fadeOut method. Afterwards, inside the complete function, we removed the element from the DOM.

Note that you can change the duration of fadeOut from “slow” to “fast” if you want to speed up the rate at which the table row is removed.

Remove the table row after the AJAX request has been successful.

To remove the table row after the AJAX request has been successful, you can place the remove code inside the success function:

In the example above, we remove the TR element if our delete AJAX request has been successful. As a result, the table row in question will not be executed if the request fails.

Obviously, you will need to modify the AJAX request above to suit your own application!

Related: Add a row to a table using JQuery.

Facebook Comments