0

I have set of table rows, each row has input elements defined with only name[] attribute,

<tr id="1">
<td><input name="billdate[]" required="required" class="form-control" placeholder="DD/MM/YYYY"></td>
<td><input class="form-control" name="amt[]" required="required"  value="0" type="text"></td>
<td><input name="gst[]" class="form-control" value="0" required="required"  type="text"></td>
<td><input name="netamt[]" class="form-control" required="required" value="0"  type="text"></td>
<td><input name="glcode[]" class="form-control" required="required" value=""  type="text"></td>
</tr> 

I have added JavaScript code to clone table row, code written below

var row = document.getElementById("1"); // find row to copy
      var table = document.getElementById("asd"); // find table to append to
      var clone = row.cloneNode(true); // copy children too
      clone.id = document.getElementById("setid").value; // change id or other attributes/contents
      table.appendChild(clone);

cloning is working fine, but the problem is that I want to assign unique ids to each input element. Is there any easy way to do this? I tried several ways to add but did not succeeded.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
user3782114
  • 542
  • 2
  • 7
  • 22

2 Answers2

0
function guid() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  }
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
    s4() + '-' + s4() + s4() + s4();
}

clone.id = guid()

It's not a true guid, but it should work fine.

Create GUID / UUID in JavaScript?

carter
  • 5,074
  • 4
  • 31
  • 40
0

Not sure if this is what your looking for. But looping through childnodes and getting input element then assigning ID seems to do the trick.

var row = document.getElementById("1"); // find row to copy
var table = document.getElementById("asd"); // find table to append to
var clone = row.cloneNode(true); // copy children too
clone.id = 'blue';//document.getElementById("setid").value;'' // change id or other attributes/contents
var children = clone.children
for( var t = 0 ; t < children.length; t++ ){
      children[t].children[0].id = 'id-'+t;
 }
//Debugging
  console.dir( clone );
  table.appendChild(clone);