I have a table which has Two button ( add & delete ). The Table contains three column (one Checkbox, one textfield and a dropdown box.) So when I click in ADD button, a new row inserted with One checkbox, One textfield and one dropdown box. What I want to do is adding one more column which will contain Serial-No. The serial-No should increase with every new row. Like...1,2,3,4 etc. Then when I want to delete a row I will tick a mark on the checkbox and press delete button and that particular row will be removed. serial-No should be re-arranged. My codes are as follows:
HTML
<div class="container">
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
<TABLE id="dataTable" width="350px" border="1">
<TR>
<TD><INPUT type="checkbox" name="chk"/></TD>
<TD><INPUT type="text" name="txt"/></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>
</TABLE>
Javascript
<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;
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>
rowIndexproperty, if that helpsif(null != chkbox && true == chkbox.checked)Assignment operator works from left into right and the same is for other operators, it should beif(chkbox !=null && chkbox.checked == true). Also check your line 10newcell.innerHTML = table.rows[0].cells[i].innerHTML;it should berows[i]instead ofrows[0]since it should update content of current row and not of the first row.rowIndexproperty. You can form a serial number by addingrowIndexof a row to a seed number.