Search code examples
javascripthtmlhtml-tableclone

Copy table row without values


<table id="mytable">

<tr id="gonnaclone">
  <td>
      <input type="text" id ="isim" name="f1" class="large" value = "" />
  </td>
  <td>
      <input type="checkbox" id ="komut" name="f2" checked/>
  </td>
</tr>

</table>

I am trying to clone table row but it is coming with the same value of the cloned row.

var table = document.getElementById("mytable");
var row = document.getElementById("gonnaclone");
var clone = row.cloneNode(true);
table.appendChild(clone);

I tried row.cloneNode(false); but it stopped working.

How can I make the value of clone row empty?


Solution

  • With jQuery you could do the following:

    $("table").append($("table")
        .find("#gonnaclone").clone()
        .find("input").val("").end());
    

    What this actually does is make a clone, find the input fields, reset the input value and append it to the table.

    But to make it even better you should also remove the ID of the cloned row (otherwise you would have duplicate IDs):

    $("table").append($("table")
        .find("#gonnaclone").clone().removeAttr("id")
        .find("input").val("").end());
    

    A complete example can be found on JSFiddle.


    If you also want to force the checkbox to be in a certain state (checked/unchecked) you could even make a bigger chain:

    $("table").append($("table")
        .find("#gonnaclone").clone().removeAttr("id")
        .find("input").val("").end()
        .find("input:checked").attr("checked", false).end());
    

    This actually unchecks the cloned row.