How can I copy all options
of one select
element to another? Please give me the easiest way, I\'m allergic to looping.
Please help me. Than
I maintain some IE11 "compatibility mode" pages which run like IE7, and the pure javascript solution above did not work for me. The first opening option tag would inexplicably be stripped using a direct innerHTML assignment.
What worked for me was explicitly appending each option in the select's option collection to the new select. In this instance it was to support an AJAX call, so I cleared the list first, but I'm sure this could append as well.
var fromSelect = document.getElementById('a');
var toSelect = document.getElementById('b');
toSelect.innerHTML = "";
for (var i = 0; i < fromSelect.options.length; i++) {
var option = fromSelect.options[i];
toSelect.appendChild(option);
}
Hopefully this helps anyone else who is stuck in compatibility mode, since this page was at the top of the list in a Google search.
$('#cloneBtn').click(function() {
var $options = $("#myselect > option").clone();
$('#second').empty();
$('#second').append($options);
$('#second').val($('#myselect').val());
});
This is used to copy the value and the innerHTML. Its better to copy the key,
value and the OPTIONS.i.e. the selected value and the options.