Following code snippet will show how to dynamically add/remove rows in Table using simple HTML and Javascript :
Source Code :
JavaScript :
Live Demo
Source Code :
HTML Table :
<table cellspacing=0 cellpadding=0 border=0 border-spacing=10px id="attributes_configuration_table">
<thead>
<tr>
<th><b>Name</b></th>
<th><b>Value</b></th>
</tr>
</thead>
<tbody>
<tr id="row_1">
<td>
<input type="text" name="attribute_name_1" id="attribute_name_1" style="margin-right:10px" autocomplete="off">
</td>
<td>
<input type="text" name="attribute_value_1" id="attribute_value_1" style="margin-right:10px" autocomplete="off">
</td>
<td><input class="new_button" id="+" name="+" onclick="addTableRow('attributes_configuration_table')" type="button" value="+">
</td>
</tr>
</tbody>
</table>
JavaScript :
var counter = 1;
function addTableRow(TableId) {
var table = document.getElementById(TableId);
counter++;
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.id = 'row_' + counter;
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "text";
element1.autocomplete = "off";
element1.name="attribute_name_" + counter;
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
var element2 = document.createElement("input");
element2.type = "text";
element2.autocomplete = "off";
element2.name="attribute_value_" + counter;
cell2.appendChild(element2);
var cell3 = row.insertCell(2);
var newButton = document.createElement("input");
newButton.className = "new_button";
newButton.type = "button";
newButton.value = '-';
newButton.onclick = removeRow;
cell3.appendChild(newButton);
}
function removeRow (id) {
var rowNode = this.parentNode.parentNode;
// Delete this node
rowNode.parentNode.removeChild(rowNode);
}
Live Demo
Comments
Post a Comment
Thank you for your comment. It'll be reviewed and posted to the blog.