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

Create Dynamic Row in a Table With HTML Using JavaScript


JavaScript JavaScript 
Ratings:
0 Comment(s)
 17143  View(s)
Rate this:

Create Dynamic Row in a Table With HTML Using JavaScript


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:

Explain Javascript function AddRow ():

<script type="text/javascript">

   function addRow(tableID) {

1.  var table = document.getElementById(tableID);

2.  var rowCount = table.rows.length;

3.  var row = table.insertRow(rowCount);

4.  var firstCell = row.insertCell(0);

5.  firstCell.innerHTML = rowCount + 1;

6.  var secondCell = row.insertCell(1);

7.  var element = document.createElement("input");

8.  element.type = "text";

9.  element.name = "txtbox[]";

10. 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 input element.

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

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

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


Don't want to miss updates? Please click the below button!

Follow MindStick