views:

28

answers:

3

Hello,

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.

A: 

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/

Plaudit Design - Web Design
Thanks, I've broken your answer over two lines because I prefer it that way.
diggersworld
A: 

Should be pretty straightforward:

var $clone = $('#options').clone();

$close.append('<option>Opt 4</option>').appendTo(document.body);

You could do it without to cache it ($clone), but that way you can hold it for later modification.

jAndy
A: 

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.

CuriousCurmudgeon