Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery clone <select> element

Tags:

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.

like image 930
diggersworld Avatar asked Oct 11 '10 13:10

diggersworld


People also ask

How do you clone an object in jQuery?

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

When using clone () which attribute can create conflict?

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.

How do you clone an element in Javascript?

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.

What is clone method in jQuery?

jQuery clone() Method The clone() method makes a copy of selected elements, including child nodes, text and attributes.


2 Answers

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/

like image 165
Plaudit Design Avatar answered Oct 15 '22 04:10

Plaudit Design


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.

like image 39
user754952 Avatar answered Oct 15 '22 05:10

user754952