Please disable your adblock and script blockers to view this page

Search this blog

Wednesday, 23 August 2017

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


Hello All

This post is about adding new row in HTML table using form entry or copy existing row to table using javascript

So here I have created a HTML page, added a form, two buttons, and a table on page and it looks like this




Here goes source of HTML form

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

Next is source of both buttons that call javascript method

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

Javascript function to add new row 

 function addNewRow() {
              //Get table object
              var comp = document.getElementById("t1");
              //Insert new row
              var row = comp.insertRow(1);
              //Set default row id
              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
              cloneRow.id = "ID";
              //Add it to table
              table.appendChild(cloneRow);
          }

Download HTML Page

Cheers :) Happy Learning 

Here you can test it- 





Name Department

No comments :

Post a Comment