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. 
 

  1. jQuery tutorials
  2. jQuery Official API Docs

HTML code: Let us start by defining the basic HTML structure of the web page.

html

filter_none

edit
close

play_arrow

link
brightness_4
code

<body>
  <div class="container pt-4">
    <div class="table-responsive">
      <table class="table table-bordered">
        <thead>
          <tr>
            <th class="text-center">Row Number</th>
            <th class="text-center">Remove Row</th>
          </tr>
        </thead>
        <tbody id="tbody">
  
        </tbody>
      </table>
    </div>
    <button class="btn btn-md btn-primary" 
        id="addBtn" type="button">
      Add new Row
    </button>
  </div>
</body>

chevron_right


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.
 



javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the
// Node.js filehandle.read() Method
  
// Denotes total number of rows.
var rowIdx = 0;
  
// jQuery button click event to add a row.
$('#addBtn').on('click', function () {
  
    // Adding a row inside the tbody.
    $('#tbody').append(`<tr id="R${++rowIdx}">
          <td class="row-index text-center">
                <p>Row ${rowIdx}</p></td>
           <td class="text-center">
            <button class="btn btn-danger remove" 
                type="button">Remove</button>
            </td>
           </tr>`);
});

chevron_right


Note: The `R${var}` is a way of concatenating a variable with a string in the new JavaScript ES6 syntax.
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: 

javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the
// Node.js filehandle.read() Method
  
// jQuery button click event to remove a row
$('#tbody').on('click', '.remove', function () {
  
    // Getting all the rows next to the 
    // row containing the clicked button
    var child = $(this).closest('tr').nextAll();
  
    // Iterating across all the rows 
    // obtained to change the index
    child.each(function () {
          
        // Getting <tr> id.
        var id = $(this).attr('id');
  
        // Getting the <p> inside the .row-index class.
        var idx = $(this).children('.row-index').children('p');
  
        // Gets the row number from <tr> id.
        var dig = parseInt(id.substring(1));
  
        // Modifying row index.
        idx.html(`Row ${dig - 1}`);
  
        // Modifying row id.
        $(this).attr('id', `R${dig - 1}`);
    });
  
    // Removing the current row.
    $(this).closest('tr').remove();
  
    // Decreasing the total number of rows by 1.
    rowIdx--;
});

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
  <title>test page</title>
  <link rel="stylesheet" href=
    integrity=
"sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh"
    crossorigin="anonymous">
  
  <script src=
  </script>
  <script src=
  </script>
  <script src=
  </script>
  
  <script>
    $(document).ready(function () {
  
      // Denotes total number of rows
      var rowIdx = 0;
  
      // jQuery button click event to add a row
      $('#addBtn').on('click', function () {
  
        // Adding a row inside the tbody.
        $('#tbody').append(`<tr id="R${++rowIdx}">
             <td class="row-index text-center">
             <p>Row ${rowIdx}</p>
             </td>
              <td class="text-center">
                <button class="btn btn-danger remove"
                  type="button">Remove</button>
                </td>
              </tr>`);
      });
  
      // jQuery button click event to remove a row.
      $('#tbody').on('click', '.remove', function () {
  
        // Getting all the rows next to the row
        // containing the clicked button
        var child = $(this).closest('tr').nextAll();
  
        // Iterating across all the rows 
        // obtained to change the index
        child.each(function () {
  
          // Getting <tr> id.
          var id = $(this).attr('id');
  
          // Getting the <p> inside the .row-index class.
          var idx = $(this).children('.row-index').children('p');
  
          // Gets the row number from <tr> id.
          var dig = parseInt(id.substring(1));
  
          // Modifying row index.
          idx.html(`Row ${dig - 1}`);
  
          // Modifying row id.
          $(this).attr('id', `R${dig - 1}`);
        });
  
        // Removing the current row.
        $(this).closest('tr').remove();
  
        // Decreasing total number of rows by 1.
        rowIdx--;
      });
    });
  </script>
</head>
  
<body>
  <div class="container pt-4">
    <div class="table-responsive">
      <table class="table table-bordered">
        <thead>
          <tr>
            <th class="text-center">Row Number</th>
            <th class="text-center">Remove Row</th>
          </tr>
        </thead>
        <tbody id="tbody">
  
        </tbody>
      </table>
    </div>
    <button class="btn btn-md btn-primary" 
      id="addBtn" type="button">
        Add new Row
    </button>
  </div>
</body>
  
</html>

chevron_right


full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.