QKWS QKWS - 2 months ago 7
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:

JavaScript:

<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);
}
</script>


The Table:

<table id="myTable">
<th>Name</th>
<th>Age</th>
<th>Gender</th>
<th>Occupation and Employer</th>
<th>Add</th>
<tr>
<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>
</tr>
</table>

Answer

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;
                cell1.appendChild(t1);
            var cell2=row.insertCell(1);
            var t2=document.createElement("input");
                t2.id = "txtAge"+index;
                cell2.appendChild(t2);
            var cell3=row.insertCell(2);
            var t3=document.createElement("input");
                t3.id = "txtGender"+index;
                cell3.appendChild(t3);
            var cell4=row.insertCell(3);
            var t4=document.createElement("input");
                t4.id = "txtOccupation"+index;
                cell4.appendChild(t4);
      index++;

}
Comments