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.
Syntax: // Create a clone of the object using the extend() method let newObj = jQuery. extend({}, obj); // Create a deep clone of the object using the deep parameter let newDeepObj = jQuery. extend(true, {}, obj);
clone() has the side-effect of producing elements with duplicate id attributes, which are supposed to be unique. Where possible, it is recommended to avoid cloning elements with this attribute or using class attributes as identifiers instead.
You call the cloneNode() method on the element you want to copy. If you want to also copy elements nested inside it, pass in true as an argument. // Get the element var elem = document. querySelector('#elem1'); // Create a copy of it var clone = elem.
jQuery clone() Method The clone() method makes a copy of selected elements, including child nodes, text and attributes.
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/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With