mola10
mola10

Reputation: 986

Copy option list from dropdownlist. JQuery

Html code

<select id="dropdwon1">
 <option value="1">Item1</option>
 <option value="2">Item2</option>
 <option value="3">Item3</option>
</select>

<select id="dropdwon2"></select>

I need copy all options from dropdown1 to dropdown2, using jQuery. Whether it is possible to copy contents simply?

Upvotes: 11

Views: 18500

Answers (4)

Pascal
Pascal

Reputation: 2405

Jquery clone is normaly the way to go but it doesn't work well with items such as select check and radio

The work around is to set the html dom attributes before cloning here is how i do it

var selects = $('form').find('select') ;
selects.each ( function ( ) {
var selvalue = $( this ).val() ;
var options = $( this ).find('option') ;
options.each ( function () {
    if ( $( this ).attr( 'value' )  == selvalue ) 
        $( this ).attr( 'selected' , true ) ; 
    });
}) ; 
$('form').clone.appendTo( '#target' )

Setting the selected dom attribute to true allow clone to copy the value effectively

Upvotes: 0

bitsmanent
bitsmanent

Reputation: 149

Can you make it "clone" currently (not initial) selected item too?

$('#dropdwon1 option').eq(1).attr('selected', 'selected');
$('#dropdwon1 option').clone().appendTo('#dropdwon2');​

Upvotes: 0

Josiah Ruddell
Josiah Ruddell

Reputation: 29831

$('#dropdwon1 option').clone().appendTo('#dropdwon2');

jsfiddle link

Upvotes: 30

Jage
Jage

Reputation: 8086

Try this:

$('#dropdwon2')[0].options = $('#dropdwon1')[0].options;

Upvotes: -1

Related Questions