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

Asked

Viewed 903 times

2

I want to copy a option or more options’s selected 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.

  • It gets a little complicated if the elements have no reference, class, value or id.

2 answers

3


Follow a suggested implementation

Jsfiddle

Whether to copy when loading the tab

$(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 when 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);
    });
});
  • 1

    jQuery was missing from your code :) I would only add one disabled in the #courses performed... Super stylish ++1

1

I ended up using it in this way, based on your answer, I just decided to try to simplify:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.