user1199657
user1199657

Reputation:

Dynamic table creation using javascript

I am using something like this to create dynamic table

    for(var i=0;i<nrRows;i++){
        row=document.createElement('tr');
        for(var j=0;j<nrCols;j++){
        cell=document.createElement('td');
        cell.appendChild(document.createTextNode(i+' '+j))
        row.appendChild(cell);
        }
        tbo.appendChild(row);
    }

Now I want the first row to be filled with column headers. And I want to give ID to each textbox in each row. How do I do so?

Upvotes: 1

Views: 3602

Answers (3)

ashi
ashi

Reputation: 108

if(i == 0)
{
    cell = document.createElement('th');
}
else
{

    cell = document.createElement('td');
    var inputFld = document.createElement('input');
    inputFld.type = "text"; //input type = textfield
    var count=table.rows.length;
    inputFld.id = "NewTb" + count;
    cell.appendChild(inputFld);
}

Upvotes: 1

Sunil Kumar B M
Sunil Kumar B M

Reputation: 2795

if(i == 0)
{
    cell = document.createElement('th');
    //give column header names
}
else
{
    cell = document.createElement('td');
    var inputFld = document.createElement('input');
    inputFld.type = "text"; //input type = textfield
    inputFld.id = "input" + i;//assign id to input field
    cell.appendChild(inputFld);
}

Upvotes: 0

nnnnnn
nnnnnn

Reputation: 150010

"Now I want the first row to be filled with column headers."

cell = document.createElement(i===0 ? 'th' : 'td');

"And I want to give ID to each textbox in each row."

What textboxes? You're not currently creating textboxes. Each id attribute should be unique, so assuming you had actually created some textboxes you could just set the id to i + "_" + j (similar to what you've already got for your .createTextNode()) so that other parts of your code could easily calculate the id that would be required to access any particular cell.

Upvotes: 3

Related Questions