How to Dynamically Add/Remove Table Rows using jQuery ?
In this article, we will learn how to dynamically add/remove rows from an HTML table using jQuery. Before reading this article, make sure you have some basic idea about jQuery. If not, you can learn it from the links mentioned below.
HTML code: Let us start by defining the basic HTML structure of the web page.
Initially, the table is empty and has no rows. We will start by adding rows dynamically inside the table body and then see how to remove a row from the table.
Adding a row:
To add a row, define a variable that keeps the count of the total number of that now exists in the table. Then we will use the jQuery “click” event to detect a click on the add row button and then use the .append() method of jQuery to add a row in the table. Each row element has been assigned an id Ri that we will later use to delete a row. Each element has a row index column and remove the button column. The code is as follows.
Removing a row: Removing a row is a bit complicated. There are two issues. Firstly, as each row is being added dynamically, we cannot detect the click of a remove button directly by using the “click” jQuery event as it is a “direct” binding which will attach the handler to already existing elements. It will not get bound to the future elements. Secondly, when we delete a row, we will need to keep up the index, i.e., if we delete the second row, the third row becomes the second and hence we need the to modify the id and the row index text.
To tackle the first problem we will use delegation and then we can handle the events of a dynamically added element.
In order to tackle the second problem, we will get all the rows next to the row where the remove button is clicked using the .nextAll() method of jQuery and then iterate across each of these elements to modify the row index and row id. The code is as follows:
This code can be modified in several ways according to the needs. For example, you can try to fix the first row in the table, such that there always exists at least one row inside the table body. One should not be able to delete the row if the row count is one.
Final code: This following code is the combination of the above sections.
HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.
CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.
You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.
Please Login to comment...