JQuery clone <select> element

2019-02-05 21:58发布

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.

5条回答
再贱就再见
2楼-- · 2019-02-05 22:44

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楼-- · 2019-02-05 22:50

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楼-- · 2019-02-05 22:50

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);
});

查看更多
霸刀☆藐视天下
5楼-- · 2019-02-05 22:52

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/

查看更多
Evening l夕情丶
6楼-- · 2019-02-05 22:53

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.

查看更多
登录 后发表回答