How to add table row in a table using jQuery?

Learn, how can we add row to an already existing table using jQuery?
Submitted by Pratishtha Saxena, on August 24, 2022

A table can be created using <table> tag in HTML. jQuery helps to make things dynamically work on a webpage. Sometimes there is a need to add or remove elements dynamically by clicking some buttons. Therefore, let's get into how to add rows to a table

Firstly, we need to figure out how to find the last row of the table so that whenever the new row is included, it needs to be added after that. For this :last selector will be used.

:last Selector – It is used to select the last element or the last child of the specified element. It returns a single value of the matched element. This will help to get the last row of the table.

Syntax:

$('#myTable tr:last')

Once we get the last row, then new row has to be added. This will be achieved by using the after() Method of jQuery.

after() Method – This jQuery method helps to append anything after a specified location or element. The content specified over here gets added up to the selected element.

Syntax:

$('selector').after();

Now, let's add some new rows to an already existing table on the click of a button.

Example to add table row in a table using jQuery

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>Document</title>
  </head>
  <body>
    <table border="1px" id="myTable">
      <tr>
        <th>S.no.</th>
        <th>Country Name</th>
        <th>Continent Name</th>
      </tr>
      <tr>
        <td>1</td>
        <td>India</td>
        <td>Asia</td>
      </tr>
      <tr>
        <td>2</td>
        <td>USA</td>
        <td>North America</td>
      </tr>
      <tr>
        <td>3</td>
        <td>England</td>
        <td>Europe</td>
      </tr>
    </table>
    <br>
    <button type="button" id="button1">Add Row</button>
  </body>

  <script type="text/javascript">
    let someValue = 4;
    $(document).ready(function(){
        $("#button1").on('click',function(){
            $('#myTable tr:last').after('<tr><td>'+someValue+'</td><td>New Row</td><td>New Row</td></tr>');
            someValue++;
        });
    })    
  </script>
</html>

Output:

Example: Add table row in a table using jQuery






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.