blog

Home / DeveloperSection / Blogs / Create Dynamic Row in a Table With HTML Using JavaScript

Create Dynamic Row in a Table With HTML Using JavaScript

Vijay Shukla28293 08-Jan-2013


This blog explains how to make a dynamic editable row in a table using html and javascript.

The contents of an html table can be added through the user inputs means when we need an editable row in my html application we just click on AddRow button and you can see that a blank editable row will appear on your screen.

HTML Code:
<html> 
<body>
    <input type="button" value="Add Row" onclick="addRow('dataTable')" />
    <table id="dataTable" width="150px" border="1">
        <tr>
            <td>
                1
            </td>
            <td>
                <input type="text" />
            </td>
        </tr>
    </table>
</body>
</html>

Javascript:
<script type="text/javascript"> 
        function addRow(tableID) {
            var table = document.getElementById(tableID);
            var rowCount = table.rows.length;
            var row = table.insertRow(rowCount);
            var firstCell = row.insertCell(0);
            firstCell.innerHTML = rowCount + 1;
            var secondCell = row.insertCell(1);
            var element = document.createElement("input");
            element.type = "text";
            element.name = "txtbox[]";
            secondCell.appendChild(element);
        }
    </script>

Output:


Create Dynamic Row in a Table With HTML Using JavaScript

Explain Javascript function AddRow ():
<script type="text/javascript">
   function addRow(tableID) {
  var table = document.getElementById(tableID);
var rowCount = table.rows.length;
  var row = table.insertRow(rowCount);
  var firstCell = row.insertCell(0);
  firstCell.innerHTML = rowCount + 1;
  var secondCell = row.insertCell(1);
var element = document.createElement("input");
element.type = "text";
  element.name = "txtbox[]";
secondCell.appendChild(element);
   }
</script>

1.       This line will store the table object with the help of table’s Id which is


used in next line of code.


2.       This line will count the row(s) in the table object.


3.       In this line we will insert the row in the table object.


4.       This line inserts a cell in the row.


5.       This line adds the cell with the help of innerHTML and rowCount + 1


increase the firstcells value.


6.       This line is also add a new cell in the row same as step no. 4.


7.       This line is creating an inputelement.


8.       This line will set the type of the elements which is created in step no.


9.        This line gives the name of the textbox’s name in array.


10.   This line will set the textbox in the second cell.


Updated 18-Sep-2014

Leave Comment

Comments

Liked By