0

I have a table with some complicated values (I mean I have to make several requests to get all the values that I want in it). I need to add rows at the end of this table and fill the cells with the same code as the existing html code.

For example, I have something like :

<table id="table_cultures">
    <tr>
        <td>Just a string</td>
        <td>Dropdown</td>
        <td><div class='foo'> something..</div></td>
    </tr>
</table>
<button id="plus_button" onclick="addRow()">+</button>

Now, in my javascript, I have something like :

function addRow(){

    var table = document.getElementById("table_cultures"); //Get the table element
    var itk = document.getElementById('foo'); //Try to get the html to duplicate

    var row = table.insertRow(-1); //Add in the end of the table

    var c1 = row.insertCell(0);
    var c2 = row.insertCell(1);
    var c3 = row.insertCell(2);


        c1.innerHTML= 'Culture';
        c2.innerHTML='test';
        c3.innerHTML=itk;

}

So, in the variable itk, I'm trying to get the html generated and pull it into the cell, bu[Object]t it displays just HTMLFormElement (because it's a table that I want to duplicate).

Is that possible to do it that way ? Or there is an other way more simple please ?

Erlaunis
  • 1,433
  • 6
  • 32
  • 50

3 Answers3

0

You shall consider cloning the row node instead of getting and setting innerHTML with some thing like this:

 var table = document.getElementById("table_cultures"); //Get the table element
    var row = document.getElementById("rowTobeCloned"); //clone the required row
    var clone = row.cloneNode(true); // copy child nodes too
    table.appendChild(clone); // append the new row to the end of the table
Arun Sharma
  • 1,331
  • 8
  • 11
  • Can you explain me why should I use this method over "innerHTML" please ? – Erlaunis May 04 '16 at 09:14
  • Simply, because cloning a node is faster than reading and resetting html . Please check this: http://stackoverflow.com/questions/676249/deep-cloning-vs-setting-of-innerhtml-whats-faster – Arun Sharma May 04 '16 at 09:58
0

At the moment you are not using jQuery in your code at all, but if you are looking for a jQuery solution you should try .clone()

$("#table_cultures td:last").clone().appendTo("#table_cultures tr");

JSFiddle

DavidKahnt
  • 452
  • 1
  • 8
  • 13
0

You using class("class='foo'") not Id ("getElementById") so it should be something like this

function addRow(){...

var itk = document.getElementsByClassName('foo')[0]; //Try to get the html to duplicate

...}