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