开发者

Copy option list from dropdownlist. JQuery

开发者 https://www.devze.com 2023-01-30 15:00 出处:网络
Html code <select id=\"dropdwon1\"> <option value=\"1\">Item1</option> <option value=\"2\">Item2</option>开发者_开发知识库

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?


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

jsfiddle link


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

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


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


Try this:

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

精彩评论

暂无评论...
验证码 换一张
取 消