JQuery clone <select> element

50,274

Solution 1

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/

Solution 2

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.

Solution 3

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());
Share:
50,274
diggersworld
Author by

diggersworld

Updated on July 09, 2022

Comments

  • diggersworld
    diggersworld almost 2 years

    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.

  • diggersworld
    diggersworld over 13 years
    Thanks, I've broken your answer over two lines because I prefer it that way.
  • dalore
    dalore almost 10 years
    Note from the docs on jquery clone, it won't clone anything that was selected: "For performance reasons, the dynamic state of certain form elements (e.g., user data typed into textarea and user selections made to a select) is not copied to the cloned elements. When cloning input elements, the dynamic state of the element (e.g., user data typed into text inputs and user selections made to a checkbox) is retained in the cloned elements." see api.jquery.com/clone