JQuery clone <select> element

自作多情 提交于 2019-12-30 02:45:09

问题


I want to clone a <select> input in HTML using JQuery.
I'm not sure how to go about it, so thought I'd ask here.

Particularly interested in the best way to write it back into the document as well.

My select element looks like this:

<select id="options">
    <option value="1">Opt 1</option>
    <option value="2">Opt 2</option>
    <option value="3">Opt 3</option>
</select>

Thanks.


回答1:


See: http://api.jquery.com/clone/

$('select#options').clone().attr('id', 'newOptions').appendTo('.blah');

appendTo(...) is only one way to insert the cloned elements. Other methods can be found here: http://api.jquery.com/category/manipulation/




回答2:


How about this?

<select id="options">
    <option value="1">Opt 1</option>
    <option value="2">Opt 2</option>
    <option value="3">Opt 3</option>
</select>

//target

<select id="options2">
</select>

$('#options').find('option').clone().appendTo('#options2');

Thanks.




回答3:


Only problem with the accepted answer is that if your select contains optgroups they will not be copied over. In that case, the easiest way I found was to just do this:

$('#options2').html($('#options').html());



回答4:


jQuery has a clone method built-in. There are many options for how to add the cloned element back in. The proper choice is dependent on your application.




回答5:


you can attr option selected true with select change, then use clone is ok.

$("#options").off("change").on("change", function() {
    var val = $(this).val();

    $(this).find("option[value=" + val + "]").attr("selected", true);
});

$("#options").off("change").on("change", function() {
    var val = $(this).val();

    $(this).find("option[value=" + val + "]").attr("selected", true);
});


来源:https://stackoverflow.com/questions/3906644/jquery-clone-select-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!