PDA

View Full Version : Cloned Select Menu


Basscyst
04-19-2005, 06:54 PM
This is handy when making dynamic forms. Will reproduce and return a duplicate of an existing select menu. Just pass the id of the select you wish to clone.


function cloneSelect(objid)
{
var sel=document.createElement('select');
obj=document.getElementById(objid);
var len=obj.childNodes.length;
for(var i=0;i<len;i++)
{
if(obj.childNodes.item(i).text)
{
var opt=document.createElement("option");
opt.value=obj.childNodes.item(i).value;
str=document.createTextNode(obj.childNodes.item(i).text);
opt.appendChild(str);
sel.appendChild(opt);
}
}
return sel;
}


Basscyst

Harry Armadillo
04-19-2005, 09:50 PM
How about .cloneNode(true)?

Basscyst
04-19-2005, 10:45 PM
I guess that works doesn't it. I was just using cloneNode() without the flag. It wasn't cloning the children, so I came up with that. Guess they thought about it already though. ;)

So now it looks like this, almost not worth posting. Definetly cleaner, but not nearly as cool. :p


function cloneSelect(objid)
{
obj=document.getElementById(objid);
var sel=obj.cloneNode(true);
return sel;
}


Basscyst

glenngv
04-20-2005, 04:49 AM
I read somewhere that when you clone a select, the selectedIndex of the new select is lost. So you have to set it after cloning.

Basscyst
04-23-2005, 01:53 AM
Yeah, but it does clone the name, so you have to set a new name too.