1

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?

3 Answers 3

3

"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.

Sign up to request clarification or add additional context in comments.

Comments

1
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);
}

Comments

0
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);
}

3 Comments

You might want to concatenate "_"+j (or something) on the end of your input ids so that every input in the row doesn't have the same id...
yes, that's why I've concatenated i to the id, even j can also be concatenated to generate unique id across the table
@SunilKumarBM - the id attribute is supposed to be unique across the entire document...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.