QKWS QKWS - 1 year ago 69
Javascript Question

How to dynamically add a table row with textbox?

I have a table where each row contains 4 cells and each cell contains a textbox
by default. I have only 1 row and a button that allows me to add an additional row every time it's clicked.

How do I dynamically add table rows containing textboxes in Javascript?

I would also like to have their textbox id change:

<input type="text" id="txtbox1" />
<input type="text" id="txtbox2" />

Right now, I have code that adds the cells:


<script type="text/javascript">
function insertRow(){
var table=document.getElementById("tbSibling");
var row=table.insertRow(2);
var cell1=row.insertCell(0);
var cell2=row.insertCell(1);
var cell3=row.insertCell(2);
var cell4=row.insertCell(3);

The Table:

<table id="myTable">
<th>Occupation and Employer</th>
<td><input type="text" id="txtName" /></td>
<td><input type="text" id="txtAge" /></td>
<td><input type="text" id="txtGender" /></td>
<td><input type="text" id="txtOccupation" /></td>
<td id="btnAdd" class="button-add" onclick="insertRow();">add</td>

Answer Source

Check with this, it's all you want, by using pure javascript. JSFIDDLE

var index = 1;
function insertRow(){
            var table=document.getElementById("myTable");
            var row=table.insertRow(table.rows.length);
            var cell1=row.insertCell(0);
            var t1=document.createElement("input");
                t1.id = "txtName"+index;
            var cell2=row.insertCell(1);
            var t2=document.createElement("input");
                t2.id = "txtAge"+index;
            var cell3=row.insertCell(2);
            var t3=document.createElement("input");
                t3.id = "txtGender"+index;
            var cell4=row.insertCell(3);
            var t4=document.createElement("input");
                t4.id = "txtOccupation"+index;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download