Add and delete table row js implementation code dynamically
This article mainly introduces the js implementation code for dynamically adding and deleting table rows. If you need it, you can refer to it and hope to help you.
The Code is as follows:
<Html>
<Head>
<Script language = "javascript">
// Add a row to the window table
Function addNewRow (){
Var tabObj = document. getElementById ("myTab"); // obtain the table for adding data
Var rowsNum = tabObj. rows. length; // obtain the current row number.
Var colsNum = tabObj. rows [rowsNum-1]. cells. length; // gets the number of rows
Var myNewRow = tabObj. insertRow (rowsNum); // Insert a new row
Var newTdObj1 = myNewRow. insertCell (0 );
NewTdObj1.innerHTML = "<input type = 'checkbox' name = 'chkarr' id = 'chkarr'" + rowsNum + "style = 'width: 20px '/> ";
Var newTdObj2 = myNewRow. insertCell (1 );
NewTdObj2.innerHTML = "<input type = 'text' name = 'nodecode' id = 'nodecode'" + rowsNum + "style = 'width: 40px 'value = '"+ rowsNum +"'/> ";
Var newTdObj3 = myNewRow. insertCell (2 );
NewTdObj3.innerHTML = "<input type = 'text' name = 'nodename' id = 'nodename'" + rowsNum + "style = 'width: 120px '/> ";
Var newTdObj4 = myNewRow. insertCell (3 );
NewTdObj4.innerHTML = "<input type = 'text' name = 'nodeper 'id = 'nodeper'" + rowsNum + "style = 'width: 60px '/> ";
}
// Delete a row in the window table
Function removeRow (){
Var chkObj = document. getElementsByName ("chkArr ");
Var tabObj = document. getElementById ("myTab ");
For (var k = 0; k <chkObj. length; k ++ ){
If (chkObj [k]. checked ){
TabObj. deleteRow (k + 1 );
K =-1;
}
}
}
</Script>
</Head>
<Body>
<Input type = "button" name = "xx" onclick = "addNewRow ();" value = "add a row"/>
<Input type = "button" name = "yy" onclick = "removeRow ();" value = "delete a row"/>
<Table width = "600px" border = "1" cellpadding = "0" cellspacing = "0" id = "myTab">
<Tr>
<Td width = "40px" class = "top-bt liebiao-c" align = "center"> operation </td>
<Td width = "40px" class = "top-bt liebiao-c" align = "center"> NO. </td>
<Td class = "top-bt liebiao-c" align = "center"> node name </td>
<Td width = "80px" class = "top-bt liebiao-c" align = "center"> node ratio </td>
</Tr>
</Table>
</Body>
</Html>