cloneNode() - Cloning Existing Form Objects
- Assigning unique ids

- Introduction
- Assigning Unique names
- Assigning Unique ids
- Retaining Values and Object States

for IE5.5+, N7+, and Mozilla 1.1

In the table id="test3" below, the text input is assigned an id as well as a name. The function addRow() is the same used on the previous page but with code added to assign new ids. Function addRow() introduces a new twist by using insertBefore(newNode,referenceNode) instead of appendChild()

<script>
inNo = 1;

function addRow(){
 var t = document.getElementById('test3');
 var tb = t.getElementsByTagName('tbody')[0];
 var tr0 = tb.childNodes[0];

 var myClone = tr0.cloneNode(true);
 var newInpt = myClone.getElementsByTagName('input');

for (i=0; i < newInpt.length; i++){
 var newName = newInpt[i].name.substring(0,newInpt[i].name.search(/\d/)) + inNo;
 // - create the new id value
 var newId = newInpt[i].id.substring(0,newInpt[i].id.search(/\d/)) + inNo;
 newInpt[i].setAttribute('name',newName);
 newInpt[i].setAttribute('value', 'name = '+newName+', id = '+newId);
 // - assign the new id to the cloned input
 newInpt[i].setAttribute('id',newId);
 }
inNo++;
// - use the next line to insert the new row at the end of the other rows
//tb.appendChild(myClone);
// - use the next line to insert the new row as the first row
tb.insertBefore(myClone,tr0);
}

// - this is the function used to highlight the selected ids in the test below
function selInp(s){
 var thisId = s.options[s.selectedIndex].value;
 var thisObj = document.getElementById(thisId);

 var t3Inp = document.getElementById('test3').getElementsByTagName('input');
 for (i=0; i < t3Inp.length; i++){
  if (t3Inp[i].type != 'button')
  t3Inp[i].style.backgroundColor = '#fff';
 }
 if (s.selectedIndex != 0)
  thisObj.style.backgroundColor = '#ccf';
}
</script>

Table id="test3"
Name
Test
Choose an id to highlight:

Here's how different browsers did on the test:
  WIN MAC
Mozilla 1.1 N7 N6 IE5.5+ Opera 6.05 N6 IE5+
Test Y Y Y Y n/a Y not tested

Retaining Values and Object States >>








PXL8 2003