Skip to content Skip to sidebar Skip to footer

Javascript Table Manipulation

I have a table with one column and about ten rows. The first column has rows with text as row headers, 'header 1', 'header 2'. The second column contains fields for the user to t

Solution 1:

Amusing exercise. Thanks to AviewAnew's hint, I could do it.

functionAddColumn(tableId)
{
  var table = document.getElementById(tableId);
  if (table == undefined) return;
  var rowNb = table.rows.length;
  // Take care of headervar bAddNames = (table.tHead.rows[0].cells.length % 2 == 1);
  var newcell = table.rows[0].cells[bAddNames ? 1 : 0].cloneNode(true);
  table.rows[0].appendChild(newcell);
  // Add the remainder of the columnfor(var i = 1; i < rowNb; i++)
  {
    newcell = table.rows[i].cells[0].cloneNode(bAddNames);
    table.rows[i].appendChild(newcell);
  }
}

with following HTML:

<inputtype="button"id="BSO"value="Add"onclick="javascript:AddColumn('TSO')"/><tableborder="1"id="TSO"><thead><tr><th>Fields</th><th>Data</th></tr></thead><tbody><tr><td>Doh</td><td>10</td></tr><tr><td>Toh</td><td>20</td></tr><tr><td>Foo</td><td>30</td></tr><tr><td>Bar</td><td>42</td></tr><tr><td>Ga</td><td>50</td></tr><tr><td>Bu</td><td>666</td></tr><tr><td>Zo</td><td>70</td></tr><tr><td>Meu</td><td>80</td></tr></tbody></table>

Solution 2:

Something along the lines of

function(table)
{
  for(var i=0;i<table.rows.length;i++)
  {
    newcell = table.rows[i].cells[0].cloneNode(true);
    table.rows[i].appendChild(newcell);
  }
}

Post a Comment for "Javascript Table Manipulation"