In this lesson I will show you how to delete a table row using jQuery. We will also highlight the row and animate the deletion. This is a really nice little script it follows on from the previous tutorial How to Add and Remove a Class using jQuery.
The demo table and working script is below. Feel free to click on the delete icons to see what happens.
The first step is to create the HTML template as follows:
Line 8: we include the Bootstrap css styling
Line 9: we include the FontAwesome icon library
Line 10: we include jQuery from Google
Lines 14 to 34: we create a simple table with 2 rows, each wth 3 columns, The third column contains the delete icon.
All that remains to do is to include the script to take care of the highlighting and deleting.
Line 3: we use the click function on the trashcan icon (it has a class of .fa-trash.alt
Line 4: we prevent the default action from taking place. The default action would be to refresh the page due to the href on the trashcan. We want to prevent that from happening
Line 5: we declare a variable called row. This is to identify the closest table row to the trash can icon that has been clicked. Since there are multiple trashcans we need to know the row of the one that has been clicked.
Line 6: we add the call .bg-danger which will colour the table row red
Lines 7 to 9: we animate the hiding of the row over 2 seconds before deleting it completely
The full code is as follows:
Did you find this lesson useful? Please leave a comment below and make a small donation to help with website running costs.
If you would like to learn more then try one of the full courses on Coding.Academy.