abby
abby

Reputation: 678

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?

Upvotes: 2

Views: 9356

Answers (2)

sanjeev
sanjeev

Reputation: 4631

You can do it this way

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

        /**
          Will Ensure that blank entry are appended in html
        **/
        var InputType = clone.getElementsByTagName("input");

        for (var i=0; i<InputType.length; i++){
         if( InputType[i].type=='checkbox'){
            InputType[i].checked = false;  
        }else{
           InputType[i].value='';               
            }
        }
        table.appendChild(clone);

Upvotes: 6

Dimitri Mestdagh
Dimitri Mestdagh

Reputation: 44745

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.

Upvotes: 3

Related Questions