My approach is a little different.
Instead of changing the selection during cloning, I just look at each select on the page for the change event, and then, if the value is changed, I add the required selected attribute to the selected <option> , so it becomes <option selected="selected"> . Since the selection is now marked in the <option> markup, it will be passed when you .clone() it.
The only code needed:
//when ANY select on page changes its value $(document).on("change", "select", function(){ var val = $(this).val(); //get new value //find selected option $("option", this).removeAttr("selected").filter(function(){ return $(this).attr("value") == val; }).first().attr("selected", "selected"); //add selected attribute to selected option });
And now you can copy the selected option in any way, and it will also copy the value.
$("#my-select").clone();
I think this solution is less customary, so you don’t have to worry if your code breaks if you change something later.
If you do not want it to be applied to each selection on the page, you can change the selector in the first line, for example:
$(document).on("change", "select.select-to-watch", function(){
pie6k Mar 25 '16 at 11:16 2016-03-25 11:16
source share