Our highest priority is to satisfy the customer through early and continuous delivery of valuable and working software.

Friday, April 27, 2007

Dynamically add and remove rows in a HTML table using Javascript

Add Row to Table

var Tbl, Tr, Td, data;

STEP:1
Tbl = document.getElementById('tbl_id');

STEP:2
Tr = Tbl.insertRow(Tbl.rows.length);
// if a table has already four rows, Tbl.rows.length = 4
// row 0, row 1, row 2, row 3
// so, new row index is 4 i.e. row 4

// you can set attributes runtime as follow.
// e.g. if you want to set "id" for newly created row.
Tr.setAttribute('id', 'some_id');

// you can apply style runtime as follow.
// e.g. if you want to set background color for newly created row.
Tr.style.backgroundColor = "#000000";

STEP:3
// next step is - to create TD
Td = Tr.insertCell(Tr.cells.length);
// initially Tr.cells.length=0; bcoz you have just new created row with no TD
// for TD also, u can set new attributes & apply styles run time; as done for row.

STEP:4
// next step is - to append data to TD for display.
// you can use either of the suggested options
// option #2 is preferable, as it will work fine on firefox and IE.
// In some case option #1 may be fail.

// option #1 e.g.
Td.innerHTML = "<input type='text' id='email' name='email' value='abc@xyz.com'>";

// option #2 e.g.
data = document.createElement('input');
data.setAttribute('type', 'text');
data.setAttribute('id', 'email');
data.setAttribute('name', 'email');
data.setAttribute('value', 'abc@xyz.com');
Td.appendChild(data);


// Repeat STEP 3 & 4 to add more columns to a row.
// Repeat STEPS 2, 3 & 4 to add more rows to table.

Remove Row from Table

var Tbl, Tr, Td, data;

STEP:1
Tbl = document.getElementById('tbl_id');

STEP:2
// this will delete last row.
Tbl.deleteRow(Tbl.rows.length - 1);

// you can pass index of you row, if you want to delete perticular row.
// e.g. if a table has four rows, Tbl.rows.length = 4
// and you want to remove 2rd row from your table.
// in this case your row index is 1
// Tbl.deleteRow(1); will remove 2nd row.

No comments:

Post a Comment