Dynamically Add and Remove HTML Table Rows using jQuery

This tutorial will help you to learn How to Dynamically Add and Remove HTML Table Rows using JavaScript and jQuery. This front-end feature is commonly used for iterated data to be saved on the database. This feature gives the end-users a better experience while using your developed app or website. User can simply add and remove HTML Table Rows without leaving the current page or refreshing/reloading the page.

I have created a simple application source code that demonstrates a simple way that meets our goal for this tutorial. The source code uses a Bootstrap v5 Framework for the design of the page and loads the jQuery Libray to run jquery scripts.

Creating the Interface

Below is the HTML Code containing the HTML Elements that are needed for this tutorial app such as the Table and buttons.

  1. <!DOCTYPE html>
  2. <html lang="en">
  3.  
  4.     <meta charset="UTF-8">
  5.     <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7.     <title>Dynamically Add and Remove Table Row</title>
  8.     <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
  9.  
  10.     <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
  11.     <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-ODmDIVzN+pFdexxHEHFBQH3/9/vQ9uori45z4JjnFsRydbmQbmL5t1tQ0culUzyK" crossorigin="anonymous"></script>
  12. </head>
  13.  
  14.     <div class="container">
  15.         <h1 class="text-center">Dynamically Add and Remove HTML Table Row</h1>
  16.         <hr>
  17.         <table class="table table-bordered" id="mytable">
  18.             <colgroup>
  19.                 <col width="10%">
  20.                 <col width="45%">
  21.                 <col width="45%">
  22.             </colgroup>
  23.             <thead>
  24.                 <tr>
  25.                     <th class="text-center">
  26.                         <div class="form-check">
  27.                             <input class="form-check-input" type="checkbox" id="SelectAll">
  28.                             <label class="form-check-label" for="SelectAll">
  29.                               Select All
  30.                             </label>
  31.                         </div>
  32.                     </th>
  33.                     <th class="text-center">Column 1</th>
  34.                     <th class="text-center">Column 2</th>
  35.                 </tr>
  36.             </thead>
  37.             <tbody>
  38.                 <tr>
  39.                     <td class="">
  40.                         <div class="form-check text-center">
  41.                             <input class="form-check-input row-item" type="checkbox">
  42.                         </div>
  43.                     </td>
  44.                     <td>12345678</td>
  45.                     <td>12345678</td>
  46.                 </tr>
  47.             </tbody>
  48.         </table>
  49.         <button class="btn btn-primary btn-sm rounded-0" id="add_row" type="button">Add Row</button>
  50.         <button class="btn btn-danger btn-sm rounded-0" id="delete_selected" type="button">Delete Selected</button>
  51.     </div>
  52. </body>
  53. </html>

The code above outputs a simple web page that contains a simple Table with 3 columns. The first column of the table contains a checkbox which will be use to identify the row item of the table to remove. The main purpose of the checkbox is to remove multiple HTML Table row at once. The table also contains a Select/Deselect All checkbox to check/uncheck the table rows at once.

The Main Script

The code below is a JavaScript code which executes the functionalities of the Buttons and Checkboxes on the HTML.

  1. $(document).ready(function() {
  2.  
  3.  
  4.     // Add Table Row
  5.  
  6.     $('#add_row').click(function() {
  7.         // Sample Data
  8.         var rand = Math.floor((Math.random() * 10) + 1);
  9.  
  10.         var tr = $("<tr>")
  11.         tr.append("<td><div class='form-check text-center'><input class='form-check-input row-item' type='checkbox'></div></td>")
  12.         tr.append(`<td>${rand}</td>`)
  13.         tr.append(`<td>${rand}</td>`)
  14.         $('#mytable tbody').append(tr)
  15.  
  16.         // Row Item Change Event Listener
  17.  
  18.         $('tr').find('.row-item').change(function() {
  19.             if ($(".row-item").length == $(".row-item:checked").length) {
  20.                 $('#SelectAll').prop('checked', true)
  21.             } else {
  22.                 $('#SelectAll').prop('checked', false)
  23.             }
  24.         })
  25.     })
  26.  
  27.     // Remove Selected Table Row(s)
  28.     $('#delete_selected').click(function() {
  29.         var count = $('.row-item:checked').length
  30.         if (count <= 0) {
  31.             alert("Please select at least 1 table row to remove first.")
  32.         } else {
  33.             $('.row-item:checked').closest('tr').remove()
  34.         }
  35.     })
  36.  
  37.     // Select All
  38.  
  39.     $('#SelectAll').change(function() {
  40.         if ($(this).is(':checked') == true) {
  41.             $('.row-item').prop("checked", true)
  42.         } else {
  43.             $('.row-item').prop("checked", false)
  44.  
  45.         }
  46.     })
  47.  
  48.     // Row Item Change Event Listener
  49.  
  50.     $('.row-item').change(function() {
  51.         if ($(".row-item").length == $(".row-item:checked").length) {
  52.             $('#SelectAll').prop('checked', true)
  53.         } else {
  54.             $('#SelectAll').prop('checked', false)
  55.         }
  56.     })
  57. })

The script above exutes the following:

  • Add New Row on the Table
  • Select/Deselect all items to remove
  • Remove Selected Table Row(s) Items

The source code above also contains a simple script for return a message when Remove button been clicked without selected Table Row

Complete Code

  1. <!DOCTYPE html>
  2. <html lang="en">
  3.  
  4.     <meta charset="UTF-8">
  5.     <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7.     <title>Dynamically Add and Remove Table Row</title>
  8.     <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
  9.  
  10.     <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
  11.     <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-ODmDIVzN+pFdexxHEHFBQH3/9/vQ9uori45z4JjnFsRydbmQbmL5t1tQ0culUzyK" crossorigin="anonymous"></script>
  12. </head>
  13.  
  14.     <div class="container">
  15.         <h1 class="text-center">Dynamically Add and Remove HTML Table Row</h1>
  16.         <hr>
  17.         <table class="table table-bordered" id="mytable">
  18.             <colgroup>
  19.                 <col width="10%">
  20.                 <col width="45%">
  21.                 <col width="45%">
  22.             </colgroup>
  23.             <thead>
  24.                 <tr>
  25.                     <th class="text-center">
  26.                         <div class="form-check">
  27.                             <input class="form-check-input" type="checkbox" id="SelectAll">
  28.                             <label class="form-check-label" for="SelectAll">
  29.                               Select All
  30.                             </label>
  31.                         </div>
  32.                     </th>
  33.                     <th class="text-center">Column 1</th>
  34.                     <th class="text-center">Column 2</th>
  35.                 </tr>
  36.             </thead>
  37.             <tbody>
  38.                 <tr>
  39.                     <td class="">
  40.                         <div class="form-check text-center">
  41.                             <input class="form-check-input row-item" type="checkbox">
  42.                         </div>
  43.                     </td>
  44.                     <td>12345678</td>
  45.                     <td>12345678</td>
  46.                 </tr>
  47.             </tbody>
  48.         </table>
  49.         <button class="btn btn-primary btn-sm rounded-0" id="add_row" type="button">Add Row</button>
  50.         <button class="btn btn-danger btn-sm rounded-0" id="delete_selected" type="button">Delete Selected</button>
  51.     </div>
  52. </body>
  53.  
  54.     $(document).ready(function() {
  55.  
  56.  
  57.         // Add Table Row
  58.  
  59.         $('#add_row').click(function() {
  60.             // Sample Data
  61.             var rand = Math.floor((Math.random() * 10) + 1);
  62.  
  63.             var tr = $("<tr>")
  64.             tr.append("<td><div class='form-check text-center'><input class='form-check-input row-item' type='checkbox'></div></td>")
  65.             tr.append(`<td>${rand}</td>`)
  66.             tr.append(`<td>${rand}</td>`)
  67.             $('#mytable tbody').append(tr)
  68.  
  69.             // Row Item Change Event Listener
  70.  
  71.             $('tr').find('.row-item').change(function() {
  72.                 if ($(".row-item").length == $(".row-item:checked").length) {
  73.                     $('#SelectAll').prop('checked', true)
  74.                 } else {
  75.                     $('#SelectAll').prop('checked', false)
  76.                 }
  77.             })
  78.         })
  79.  
  80.         // Remove Selected Table Row(s)
  81.         $('#delete_selected').click(function() {
  82.             var count = $('.row-item:checked').length
  83.             if (count <= 0) {
  84.                alert("Please select at least 1 table row to remove first.")
  85.            } else {
  86.                $('.row-item:checked').closest('tr').remove()
  87.            }
  88.        })
  89.  
  90.        // Select All
  91.  
  92.        $('#SelectAll').change(function() {
  93.            if ($(this).is(':checked') == true) {
  94.                $('.row-item').prop("checked", true)
  95.            } else {
  96.                $('.row-item').prop("checked", false)
  97.  
  98.            }
  99.        })
  100.  
  101.        // Row Item Change Event Listener
  102.  
  103.        $('.row-item').change(function() {
  104.            if ($(".row-item").length == $(".row-item:checked").length) {
  105.                $('#SelectAll').prop('checked', true)
  106.            } else {
  107.                $('#SelectAll').prop('checked', false)
  108.            }
  109.        })
  110.    })
  111.  
  112. </html>

DEMO VIDEO

That's it! Now you can test the source code on your end and see if it meets our goal for this tutorial. I hope this will help you with what you are looking for and for your future Web Application Projects.

Explore more on this website for more Tutorials and Source Codes.

Happy Coding :)

Add new comment