My last two blog posts showed you how to add rows to an HTML table. Now, let’s learn how to delete a row from a table. In order to accomplish this you will need to add a ‘Delete’ button to each row of the table.
The HTML for this sample is similar to my last blog post, with the addition of a new <th> to allow for a column in which you place a ‘Delete’ button. I have highlighted the change in bold in the code below.
Figure 1: Add a delete button to allow a user to delete a row from the table
Adding a Row with a Delete Button
When you add the user input data to the row in the table, you also need to add on the additional column with a button. The button will also have its onclick event filled in with the name of a function to call to delete a row in the table. Here is the addPersonToTable() function with the additional code.
You can see in the code highlighted in bold above that you create a <button> in the last column that has the onclick event filled in with a call to a function named deletePerson(). Pass in ‘this’ to the function so the function can figure out which row the button is in, as this is the row we need to delete.
Delete a Row
The deletePerson() function is very simple. The instance of the ‘Delete’ button is passed to this function. From that you can use the jQuery function parents() to locate the button’s containing <tr> tag. Once you locate that <tr> tag you use the remove() function to eliminate that row from the table.
Deleting a row from a table is a single line of code. It is just a matter of figuring out which row you are in, then applying the remove() function to that row. When you append a new row, you create a new button for the delete functionality that can call a function to perform the delete of the current row.