I have a form where the user can select one of seven days for each of eight events. I found code that should let me copy the dates from one select to another, but it deletes and moves every other option to the new select dropdown instead of copying the entire list of options.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<div>
<select id="Sel1">
<option value="1">06/01/24</option>
<option value="2">06/02/24</option>
<option value="3">06/03/24</option>
<option value="4">06/04/24</option>
<option value="5">06/05/24</option>
<option value="6">06/06/24</option>
<option value="7">06/07/24</option>
</select>
<select id="Sel2"></select>
</div>
</body>
<script>
var fromSelect = document.getElementById("Sel1");
var toSelect = document.getElementById("Sel2");
toSelect.innerHTML = "";
for (var i = 0; i < fromSelect.options.length; i++)
{
toSelect.appendChild(fromSelect.options[i]);
}
</script>
</html>
4
Answers
You need to use
cloneNode
to create copy of original select options.I think what you’re expecting here is
.appendChild
inserting the child nodes (thefromSelect.options[i]
) into some "child node list". It’s confusing: why are the nodes mysteriously vanishing?When you use
.appendChild
, what actually is happening is that the parent of the child node is being set to the parent node. In other words,parent.appendChild(child)
is the inverse ofchild.setParent(parent)
. The fix for this, then, is to clone the node before setting the child of the parent.no need for a loop here. if you want two exact same options you can pass the innerHTML of first select box to the second one.
You just need to loop through the options in reverse:
You can run the snippet to see it working: