Add Remove Row in HTML Table Using Javascript
We have created a HTML form with Name and Mark input field. When user clicked '+' button new row will be added. As well as, when user clicked '-' button current row will be removed.
Example
<html> <head> <title>Add,Remove Row in HTML Table Using Javascript</title> </head> <body> <table> <thead> <tr> <th>SNo</th> <th>Name</th> <th>Mark</th> <th>Add</th> <th>Remove</th> </tr> </thead> <tbody id="tbl"> <tr> <td class='sno'>1</td> <td><input type='text' name=''></td> <td><input type='text' name=''></td> <td><input type='button' value='+' onclick='add_row()' ></td> <td><input type='button' value='-' onclick='remove_row(this)'></td> </tr> </tbody> </table> <script src='script.js' ></script> </body> </html>Try it Yourself
script.js
function add_row() { var sno=document.querySelectorAll(".sno").length; sno++; var tr=document.createElement("tr"); tr.innerHTML="<td class='sno'>"+sno+"</td> <td><input type='text'class='form-control'></td> <td><input type='text'class='form-control'></td> <td><input type='button' value='+' onclick='add_row()' class='btn btn-success btn-xs'></td> <td><input type='button' value='-' onclick='remove_row(this)' class='btn btn-danger btn-xs'></td>"; document.getElementById("tbl").appendChild(tr); } function remove_row(e) { var n=document.querySelector("#tbl").querySelectorAll("tr").length; if(n>1&&confirm("Are You Sure")==true){ var ele=e.parentNode.parentNode; ele.remove(); serial_no(); } } function serial_no(){ var cls=document.querySelectorAll(".sno"); for(var i=0;i<cls.length;i++) { cls[i].innerHTML=i+1; } }Try it Yourself