kockburn
kockburn

Reputation: 17606

How to clone select options without cloning the select

Say I have a select:

<select id="mySelect">
 <option value="1">First</option>
 <option value="2">Second</option>
 <option value="3">Third</option>
</select>

I would like to clone all the options without having to clone the select. Is this possible? Cloning the select is not possible in my situation.

I thought of doing something like this:

$('#mySelect').html().clone();

but that did not work.

Update:

I have a select that will change over time. I have a second select in a modal. When the modal is called, I need to update the modal's select with the same options as the first modal. Both selects have different attributes, thus I can't clone the select.

Upvotes: 2

Views: 5542

Answers (3)

Benjamin Ray
Benjamin Ray

Reputation: 1870

The most straightforward way to copy the options from your primary select to the secondary select is to use html() as follows:

var options = $('#mySelect').html();
$('#mySelect2').html(options);

Or in one line:

$('#mySelect2').html($('#mySelect').html());

If you want to manipulate the options before copying to the other select, then you could use clone() to get an array of the individual select options as jQuery objects and alter the array before copying the entires to the other select. However, based on your updated requirement of simply copying the options from one select to another, using clone would definitely be overkill. But this is how you would do it:

var optionsArr = $('#mySelect option').clone();
console.log(optionsArr); // See the contents
// Manipulate and populate other select as needed

Upvotes: 7

Anderson Madeira
Anderson Madeira

Reputation: 430

You can use clone() to generate the clones then appendTo to append the new option elements to a new select and then use appendTo again to append the new select to the body. This little trick works like a charm:

$('#'+original_id+' option').clone().appendTo($('<select id="'+new_id+'">').appendTo('body'));

Considering that you are appending the copy elements to the end of the body.

This is a demo that shows how you can generate the copies:

https://jsfiddle.net/m323ww1p/

Upvotes: 0

user2085955
user2085955

Reputation: 104

Give this a shot

$('#mySelect option').clone()

Upvotes: 2

Related Questions