Javascript: How To Copy All Options From One Select Element To Another?
Solution 1:
One of the easiest ways without looping, is using jquery
(select1
= id of select 1, select2
= id of select 2):
$('#select1 option').clone().appendTo('#select2');
Without jquery
:
var select1 = document.getElementById("select1");
var select2 = document.getElementById("select2");
select2.innerHTML = select2.innerHTML+select1.innerHTML;
Solution 2:
html:
<selectid="selector_a"><option>op 1</option><option>op 2</option></select><selectid="selector_b"><option>op 3</option><option>op 4</option></select>
javascript:
var first = document.getElementById('selector_a');
var options = first.innerHTML;
var second = document.getElementById('selector_b');
var options = second.innerHTML + options;
second.innerHTML = options;
Solution 3:
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.
Solution 4:
use jQuery foreach?
$("#the-id option").each(function() {
var val = $(this).val();
var txt = $(this).html();
$("the-other-id").append(
$('<option></option>').val(val).html(txt);
);
});
Solution 5:
you can do that easily via jquery:
<select id="sel1">
<option>1</option><option>2</option><option>3</option>
</select>
<selectid="sel2"><option>1</option><option>2</option><option>3</option></select>
$(document).ready(function(){
$("#sel2").html($("#sel1").html());
});
Post a Comment for "Javascript: How To Copy All Options From One Select Element To Another?"