Add/Remove dynamic rows in HTML table
<script language="javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
if(rowCount <= 1) {
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
}
</script>
<input onclick="addRow('dataTable')" type="button" value="Add Row" />
<input onclick="deleteRow('dataTable')" type="button" value="Delete Row" />
<table border="1" id="dataTable">
<tbody>
<tr>
<td><input name="chk" type="checkbox" /></td>
<td><input name="txt" type="text" /></td>
<td><select name="country">
<option value="in">India</option>
<option value="de">Germany</option>
<option value="fr">France</option>
<option value="us">United States</option>
<option value="ch">Switzerland</option>
</select>
</td>
</tr>
</tbody></table>
No comments:
Post a Comment