Copy a selected option from a select multiple to another select multiple with jquery

1

I want to copy a option or more selected options from a select multiple to another select multiple with jquery.

<select id='cursos' multiple>
<option selected>curso 1</option>
<option selected>curso 2</option>
<option>curso 3</option>
<option>curso 4</option>
</select>


<select id='cursosrealizados' multiple>
<option>curso 1</option>
<option>curso 2</option>
</select>

If anyone has any ideas or suggestions, thank you.

    
asked by anonymous 08.10.2014 / 00:50

2 answers

2

Following is a suggested implementation

JSFiddle

If you want to copy when loading page

$(document).ready(function(){
    $('#cursosrealizados').html('');//limpa cursos realizados
    //faz loop pelas opcoes selecionads no select de cursos
    $('#cursos option:selected').each(function() {
       //clona a opcao selecionada
       var opt = $(this).clone(true).prop('selected',true);
       //coloca no select de cursos realizados
       $('#cursosrealizados').append(opt);
    });
});

If you want to copy by selecting

$('#cursos').on('change', function(){
    $('#cursosrealizados').html('');//limpa cursos realizados
    //faz loop pelas opcoes selecionads no select de cursos
    $('#cursos option:selected').each(function() {
       //clona a opcao selecionada
       var opt = $(this).clone(true).prop('selected',true);
       //coloca no select de cursos realizados
       $('#cursosrealizados').append(opt);
    });
});
    
08.10.2014 / 01:57
0

I ended up using this way, based on your answer, I just tried to simplify:

$("#cursos option:selected" ).each(function() {  
    $("#cursosrealizados").append("<option>"+$(this).text()+"</option>");
});
    
08.10.2014 / 23:20