user3344186
user3344186

Reputation: 191

How to insert textbox in table?

I have created a html table, via a button I have given the possibility to dynamically add more rows to the table. The problem is that I do not know how to add 3 textbox and one input type number (the input type number must belong to the cell 3), one for each cell created dynamically. This is my function:

function Add()
{
var tableRef = document.getElementById('tabella').getElementsByTagName('tbody')[0];

// Insert a row in the table at the last row
var newRow   = tableRef.insertRow(tableRef.rows.length);

// Insert a cell in the row at index 0
var newCell  = newRow.insertCell(0);
var newCell1 = newRow.insertCell(1);
var newCell2 = newRow.insertCell(2);
var newCell3 = newRow.insertCell(3);

// Append a text node to the cell
var newText  = document.createTextNode('New row')
newCell.appendChild(newText);

}

Upvotes: 0

Views: 4376

Answers (2)

Saravanan
Saravanan

Reputation: 11

if you are using jQuery:

var table = $("#id of your table");

var tr = $("<tr />");
for(var i=0; i<3; i++){
   var td = $("<td />");
   if(i==0) {
    var inp = $("<input />").attr("type", "text");
    td.append(inp);
   }
   tr.append(td);
}
table.append(tr);

Upvotes: 1

Yauheni Leichanok
Yauheni Leichanok

Reputation: 1769

I hope I understood the question correctly. Put this code inside of your Add function.

var input = document.createElement('input'),
    input1 = document.createElement('input'),
    input2 = document.createElement('input'),
    input3 = document.createElement('input');

input.type = 'text';
input1.type = 'text';
input2.type = 'text';
input3.type = 'number';

newCell.appendChild(input);
newCell1.appendChild(input1);
newCell2.appendChild(input2);
newCell3.appendChild(input3);

Upvotes: 1

Related Questions