Pages

Thursday, August 11, 2011

Dynmically creating a table using Javascript and adding rows to it

For this you need to first of all define an empty html table element with an id property at least to refer to it my dummy was.
table
tr
th /th
th /th
/tr
tr
td /td
td /td
/tr
/table

Written without tags so that it is not interpreted by blog as html.

My table has a header row and a normal row

The table rows starts from index 0.You can use following code from a js file or directly on an html file.
(I recommend js file helps in re usability of code)

var tbl=document.getElementByid('tbl');
//Get the last row

var lastrow=tbl.rows.length

//since I already have a header row in my table and a row manually added so in my case //new row will be equal to last row (table length does not includes the last row)

var iteration=lastrow;
//create a new row
row=tbl.insertRow(lastrow);

//leftcell
//general text node to show the Sno's
var cellleft=row.insertcell(0);
var textnode=document.CreatetextNode(value of the node);
cellleft.appendChild(textnode);

//rightcell
//creation of a textbox node
var cellright=row.insertCell(1);
var el=document.CreateElement('input');
el.type='text';
el.name='name';
el.id='id';
cellright.appendChild(el);

you can add more columns by incrementing index in var cellright=row.insertCell(1);

One of my columns required to create a list dynamically..since I need the whole list and so I cloned the same from my first row(it was the only need for which I had to create a row manually)

To clone an element use the following
elsource=document.getElementById('list element');
eldestination=elsource.clone();
eldestination.name='new list name'
eldestination.id='new id'

So that's how we can dynamically add rows to a table....

1 comment:

  1. Just an Update
    eldestination=elsource.cloneNode();
    is used to clone an object in HTML DOM MODEL

    ReplyDelete