Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy <option> from one <select> to another?

Tags:

jquery

var $options = $("#myselect > option").clone();

$('#secondSelectId').append($options);

Live DEMO


<select multiple="true" class="multiselect1" name="myselecttsms1">
    <option value="1" rel="0" title="One">One</option>
    <option value="2" rel="1" title="Two">Two</option>            
    <option value="4" rel="3" title="Four">Four</option>
    <option value="5" rel="4" title="Five">Five</option>
    <option value="6" rel="5" title="Six">Six</option>
</select>

<select multiple="true" class="multiselect2" name="myselecttsms2" size="6">

</select>

<button class="add">Add</button>
<button class="addAll">Add All</button>
<button class="remove">Remove</button>
<button class="removeAll">Remove All</button>

jQuery:

$('.add').on('click', function() {
    var options = $('select.multiselect1 option:selected').sort().clone();
    $('select.multiselect2').append(options);
});
$('.addAll').on('click', function() {
    var options = $('select.multiselect1 option').sort().clone();
    $('select.multiselect2').append(options);
});
$('.remove').on('click', function() {
    $('select.multiselect2 option:selected').remove();
});
$('.removeAll').on('click', function() {
    $('select.multiselect2').empty();
});

Sample Workout


There is an even easier way to do this:

var options = $("#myOldSelect").html();
$('#myNewSelect').html(options);

This is really handy if you want to add the new Select to the DOM with the copied options already included:

var options = $("#myOldSelect").html();
$("#domLocation").append("<select id='myNewSelect'>" + options + "</select");

$('#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.