Showing posts with label HTML. Show all posts
Showing posts with label HTML. Show all posts

Wednesday, July 9, 2014

Dynamically Add/Remove Rows in HTML Table Using Javascript

Following code snippet will show how to dynamically add/remove rows in Table using simple HTML and Javascript :

Source Code :
 HTML Table :  
 <table cellspacing=0 cellpadding=0 border=0 border-spacing=10px id="attributes_configuration_table">  
       <tr id="row_1">          
         <input type="text" name="attribute_name_1" id="attribute_name_1" style="margin-right:10px" autocomplete="off">                  
         <input type="text" name="attribute_value_1" id="attribute_value_1" style="margin-right:10px" autocomplete="off">          
       <td><input class="new_button" id="+" name="+" onclick="addTableRow('attributes_configuration_table')" type="button" value="+">  

JavaScript :
 var counter = 1;  
 function addTableRow(TableId) {  
   var table = document.getElementById(TableId);  
   var rowCount = table.rows.length;  
   var row = table.insertRow(rowCount); = 'row_' + counter;  
   var cell1 = row.insertCell(0);  
   var element1 = document.createElement("input");  
   element1.type = "text";  
   element1.autocomplete = "off";"attribute_name_" + counter;  
   var cell2 = row.insertCell(1);  
   var element2 = document.createElement("input");  
   element2.type = "text";  
   element2.autocomplete = "off";"attribute_value_" + counter;  
   var cell3 = row.insertCell(2);  
   var newButton    = document.createElement("input");  
   newButton.className = "new_button";  
   newButton.type   = "button";  
   newButton.value   = '-';  
   newButton.onclick  = removeRow;  
 function removeRow (id) {  
   var rowNode = this.parentNode.parentNode;  
   // Delete this node  

Live Demo