Added a simple button to the page. When the user clicks on the button, we invoke fnAddRows where we get user input from product controls and add them to a HTML table tblProducts.
<html> <head runat="server"> <title></title> <link type="text/css" rel="Stylesheet" href="Styles.css" /> <script language="javascript" type="text/javascript"> var ctlTableProductsID = '<%=tblProducts.ClientID%>'; //tblproducts client ID var ctlTableProducts; function fnAddRow() { if (ctlTableProducts == null) { //get reference to the table control ctlTableProducts = document.getElementById(ctlTableProductsID); } //fetch current row count var tableRowCount = ctlTableProducts.rows.length; //insert new row into the table var row = ctlTableProducts.insertRow(tableRowCount); var cell, element; //insert new cell at index 0 into the newly created row cell = row.insertCell(0); //fetch the product id entered by the user and set it to the 1st cell cell.innerHTML = document.getElementById("tbxProductID").value; //insert new cell at index 1 into the newly created row cell = row.insertCell(1); //fetch the product number entered by the user and set it to the 2nd cell cell.innerHTML = document.getElementById("tbxProductNumber").value; //insert new cell at index 2 into the newly created row cell = row.insertCell(2); //fetch the product name entered by the user and set it to the 3rd cell cell.innerHTML = document.getElementById("tbxProductName").value; //insert new cell at index 3 into the newly created row cell = row.insertCell(3); cell.align = "right"; //fetch the product id entered by the user and set it to the fourth cell cell.innerHTML = document.getElementById("tbxPrice").value; } </script> </head> <body> <form id="form1" runat="server"> <div> <table> <tr><td>ProductID:</td><td><asp:TextBox ID="tbxProductID" runat="server"/></td></tr> <tr><td>Product Number:</td><td><asp:TextBox ID="tbxProductNumber" runat="server"/></td></tr> <tr><td>Product Name:</td><td><asp:TextBox ID="tbxProductName" runat="server"/></td></tr> <tr><td>Product Price:</td><td><asp:TextBox ID="tbxPrice" runat="server"/></td></tr> </table> <a href="javascript:fnAddRow();">Add Row</a> <table id="tblProducts" runat="server" class="tableClass"> <tr> <th>Product ID</th><th>Product Number</th> <th>Product Name</th><th>Price</th> </tr> </table> </div> </form> </body> </html>
Run the application and you would see the following page
Enter product attributes in the input controls as shown below:
Click on “Add Row” and a new row is created from user’s input and is added to the table.
The post How to Add new row to Table using Javascript appeared first on Everything Technical.