Jquery Clone Element

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.

1

5 Answers

See:

$('select#options').clone().attr('id', 'newOptions').appendTo('.blah');

appendTo(...) is only one way to insert the cloned elements. Other methods can be found here:

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.

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

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.

you can attr option selected true with select change, then use clone is ok.

$("#options").off("change").on("change", function() {
    var val = $(this).val();

    $(this).find("option[value=" + val + "]").attr("selected", true);
});
$("#options").off("change").on("change", function() {
    var val = $(this).val();

    $(this).find("option[value=" + val + "]").attr("selected", true);
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest