Add new row and copy existing row to HTML table using JavaScript

Sharing is Caring

Hello All
This post is about adding a new row in HTML table using form entry or copy existing row to the table using javascript. So here I have created an HTML page, added a form, two buttons, and a table on the page and HTML page looks like this

HTML table

Here goes source of HTML form that is shown above

<form> <span><label>
Name<input type="text" id="it1" />
<br/> <span><label>
Department<input type="text" id="it2" />

Next is the source of both buttons that call the javascript method in order to create a new row

<button onclick="copyTableRow()">Copy Row</button>

<button onclick="addNewRow()">Add row to table</button>

Javascript function to add a new row 

 function addNewRow() {
              //Get table object
              var comp = document.getElementById("t1");
              //Insert new row
              var row = comp.insertRow(1);
              //Set default row id
     = "r1";
              //Add columns in row
              var column1 = row.insertCell(0);
              var column2 = row.insertCell(1);

//Set input text value in columns of row
column1.innerHTML = document.getElementById("it1").value;
column2.innerHTML = document.getElementById("it2").value;

//Empty form fields
document.getElementById("it1").value = "";
document.getElementById("it2").value = "";

Javascript function to copy row

function copyTableRow() {
              //Get Row object
              var row = document.getElementById("r1");
              //Get table object
              var table = document.getElementById("t1");
              //Create clone row
              var cloneRow = row.cloneNode(true);
              //Set Id for new row
     = "ID";
              //Add it to table

All done, Use this code in an HTML page and check yourself, Or click on below link and download a sample HTML page for reference.

Download HTML Page

Cheers 🙂 Happy Learning 

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *