JavaScript table manipulation

I have a table with one column and about ten rows. The first column contains rows with text in the form of row headings, "heading 1", "heading 2". The second column contains fields for user input (text fields and check boxes).

I want to have a button at the top that says "Add New ..." and create a third column with the same fields as the first column. If the user clicks on it again, he will create another empty column with fields (as in the second column).

Does anyone know of an efficient way to manage the DOM to achieve this?

I'm experimenting with divand TABLES, but I'm on my third day of it, and it seems harder than it should be.

+3
source share
2

. AviewAnew .

function AddColumn(tableId)
{
  var table = document.getElementById(tableId);
  if (table == undefined) return;
  var rowNb = table.rows.length;
  // Take care of header
  var 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 column
  for(var i = 1; i < rowNb; i++)
  {
    newcell = table.rows[i].cells[0].cloneNode(bAddNames);
    table.rows[i].appendChild(newcell);
  }
}

HTML:

<input type="button" id="BSO" value="Add" onclick="javascript:AddColumn('TSO')"/>
<table border="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>
+3

-

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

Source: https://habr.com/ru/post/1697877/


All Articles